repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
outillage/oto-tools
|
internal/publishrunner/create_config.go
|
<reponame>outillage/oto-tools
package publishrunner
import (
"errors"
"fmt"
"io/ioutil"
"github.com/aevea/oto-tools/internal/npm"
)
func createConfigFile(path, registry, token, owner string) error {
contents := fmt.Sprintf("%s:_authToken=%s", registry, token)
if registry == npm.GHRegistry {
if owner == "" {
return errors.New("github package registry requires an owner")
}
contents += fmt.Sprintf("\nregistry=https://npm.pkg.github.com/%s", owner)
}
return ioutil.WriteFile("./.npmrc", []byte(contents), 0777)
}
|
techbrick-ftc/team4234
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/mains/MainDrive.java
|
<filename>TeamCode/src/main/java/org/firstinspires/ftc/teamcode/mains/MainDrive.java
package org.firstinspires.ftc.teamcode.mains;
import com.acmerobotics.dashboard.FtcDashboard;
import com.acmerobotics.dashboard.telemetry.TelemetryPacket;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit;
import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder;
import org.firstinspires.ftc.robotcore.external.navigation.AxesReference;
import org.firstinspires.ftc.teamcode.libraries.Alexi;
import org.firstinspires.ftc.teamcode.libraries.FieldCentric;
import org.firstinspires.ftc.teamcode.libraries.TeleAuto;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@TeleOp(name="Driving", group="drive")
public class MainDrive extends LinearOpMode implements TeleAuto {
private Alexi robot = new Alexi();
private int[] wobblePositions = {0, -770, -1400, -1750};
private double wobbleSpeed = 0;
private int wobblePosition = 0;
private boolean wobbleWait = false;
private final FieldCentric centric = new FieldCentric();
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
ScheduledFuture<?> pushEvent = null;
private final FtcDashboard dashboard = FtcDashboard.getInstance();
private final TelemetryPacket packet = new TelemetryPacket();
public void runOpMode() {
robot.init(hardwareMap);
boolean pusherWait = false;
boolean shooterOn = false;
boolean shooterWait = false;
double shooterSpeed = 0;
double shooterTempSpeed = 2500;
boolean shooterSpeedWait = false;
boolean slow = false;
boolean slowWait = false;
double xSpeed = 0;
double ySpeed = 0;
double turnSpeed = 0;
centric.setUp(robot.motors, robot.angles, robot.imu);
startScheduler();
waitForStart();
robot.pusher.setPosition(0.9);
while (opModeIsActive()) {
if (gamepad1.back) {
centric.resetAngle();
}
xSpeed = gamepad1.left_stick_x;
ySpeed = -gamepad1.left_stick_y;
turnSpeed = -gamepad1.right_stick_x;
if (gamepad1.right_bumper && !slowWait) {
slow = !slow;
slowWait = true;
} else if (!gamepad1.right_bumper) {
slowWait = false;
}
if (slow) {
xSpeed /= 2;
ySpeed /= 2;
turnSpeed /= 2;
}
centric.gyro(robot.imu.getAngularOrientation(AxesReference.EXTRINSIC, AxesOrder.XYZ, AngleUnit.RADIANS).thirdAngle);
centric.Drive(gamepad1.left_stick_x, -gamepad1.left_stick_y, -gamepad1.right_stick_x);
if (gamepad2.y && !shooterWait) {
shooterOn = !shooterOn;
shooterWait = true;
} else if (!gamepad2.y) {
shooterWait = false;
}
if (shooterOn) {
shooterSpeed = shooterTempSpeed;
} else { shooterSpeed = 0; }
telemetry.addData("Gamepad2 y", gamepad2.y);
robot.shooter.setVelocity(shooterSpeed);
if (gamepad2.right_bumper && !shooterSpeedWait) {
if (shooterTempSpeed != 2500) {
shooterTempSpeed += 100;
shooterSpeedWait = true;
}
} else if (gamepad2.left_bumper && !shooterSpeedWait) {
if (shooterTempSpeed != 1000) {
shooterTempSpeed -= 100;
shooterSpeedWait = true;
}
} else if (!gamepad2.left_bumper && !gamepad2.right_bumper) {
shooterSpeedWait = false;
}
telemetry.addData("Shooter temp speed", shooterTempSpeed);
telemetry.addData("Shooter speed", robot.shooter.getVelocity());
if (robot.shooter.getVelocity() >= shooterTempSpeed) {
telemetry.addLine("READY FIRE");
} else {
telemetry.addLine("No fire");
}
if (gamepad2.a && !pusherWait && pushEvent.isDone()) {
robot.pusher.setPosition(0.1);
pusherWait = true;
schedulePusher();
} else {
pusherWait = false;
}
robot.wobbleMotor.setPower(gamepad2.left_stick_x);
if (gamepad2.x) {
robot.wobbleServo.setPosition(-1);
} else if (gamepad2.b) {
robot.wobbleServo.setPosition(1);
}
if (gamepad2.dpad_right && wobblePosition < 3 && !wobbleWait) {
wobblePosition++;
wobbleWait = true;
} else if (gamepad2.dpad_left && wobblePosition > 0 && !wobbleWait) {
wobblePosition--;
wobbleWait = true;
} else if (!gamepad2.dpad_right && !gamepad2.dpad_left) { wobbleWait = false; }
robot.wobbleMotor.setTargetPosition(wobblePositions[wobblePosition]);
if (robot.wobbleMotor.isBusy()) {
robot.wobbleMotor.setVelocity(800);
} else {
robot.wobbleMotor.setVelocity(0);
}
double intakePower = gamepad1.right_trigger - gamepad1.left_trigger;
robot.intake.setPower(intakePower);
telemetry.update();
}
}
private void startScheduler() {
pushEvent = executorService.schedule(() -> {}, 0, TimeUnit.MILLISECONDS);
}
private void schedulePusher() {
pushEvent = executorService.schedule(() -> robot.pusher.setPosition(0.9), 1000, TimeUnit.MILLISECONDS);
}
}
|
ShuffleZZZ/ITMO
|
AlgorithmsandDataStructures/2ndLab/task10d.cpp
|
#include <fstream>
using namespace std;
int main(){
ifstream in;
in.open("bureaucracy.in");
ofstream out;
out.open("bureaucracy.out");
int n,m,s,round;
in>>n>>m;
int a[n];
for(int i=0;i<n;i++){
in>>a[i];
}
while ((m>=n) and (n>0)){
round=m/n;
m=m%n;
s=0;
for(int i=0;i<n;i++){
a[i]-=round;
if(a[i]<0){
m-=a[i];
}
if(a[i]>0){
a[s++]=a[i];
}
}
n=s;
}
s=0;
if(n==0) {
out<<"-1";
} else {
for(int i=0;i<m;i++){
a[i]-=1;
if(a[i]==0){
s++;
}
}
out<<n-s<<'\n';
for(int i=m;i<n+m;i++){
round=i/n;
s=i%n;
if(!round or (a[s]!=0)){
out<<a[s]<<' ';
}
}
}
in.close();
out.close();
}
|
stratacode/system
|
system/src/sc/lang/java/AbstractTemplateParameters.java
|
<filename>system/src/sc/lang/java/AbstractTemplateParameters.java
/*
* Copyright (c) 2021. <NAME>. All Rights Reserved.
*/
package sc.lang.java;
public class AbstractTemplateParameters {
public static boolean emptyString(String str) {
return str == null || str.length() == 0;
}
public static String formatString(String str) {
if (str == null)
return "null";
else
return '"' + str + '"';
}
public static String formatStringArray(String[] strarr) {
StringBuilder sb = new StringBuilder();
sb.append("new String[] {");
int i = 0;
for (String str:strarr) {
if (i != 0)
sb.append(",");
sb.append(formatString(str));
i++;
}
sb.append("}");
return sb.toString();
}
}
|
SmarterEye/libsmartereye2
|
src/usb/usb_messenger.cc
|
<reponame>SmarterEye/libsmartereye2<filename>src/usb/usb_messenger.cc<gh_stars>1-10
// Copyright 2020 Smarter Eye Co.,Ltd. All Rights Reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "usb_messenger.h"
#include "usb_handle.h"
#include "easylogging++.h"
namespace libsmartereye2 {
namespace platform {
UsbMessenger::UsbMessenger(const std::shared_ptr<UsbDevice> &device, std::shared_ptr<UsbHandle> handle)
: device_(device), handle_(handle) {
}
int UsbMessenger::control_transfer(int request_type, int request, int value, int index,
uint8_t *buffer, uint32_t length, uint32_t &transferred, uint32_t timeout_ms) {
auto status = libusb_control_transfer(handle_->get(),
request_type, request, value, index, buffer, length, timeout_ms);
if (status < 0) {
std::string strerr = libusb_error_name(status);
LOG(WARNING) << "control_transfer returned error, index: " << index << ", error: " << strerr;
return status;
}
transferred = static_cast<uint32_t>(status);
return LIBUSB_SUCCESS;
}
int UsbMessenger::bulk_transfer(const SeUsbEndpoint &endpoint, uint8_t *buffer,
uint32_t length, uint32_t &transferred, uint32_t timeout_ms) {
int actual_length = 0;
int sts = 0;
if (endpoint->getType() == SE2_USB_ENDPOINT_BULK)
sts = libusb_bulk_transfer(handle_->get(), endpoint->getAddress(), buffer, length, &actual_length, timeout_ms);
else if (endpoint->getType() == SE2_USB_ENDPOINT_INTERRUPT)
sts = libusb_interrupt_transfer(handle_->get(), endpoint->getAddress(), buffer, length, &actual_length, timeout_ms);
else {
LOG(ERROR) << "Invalid transfer type " << endpoint->getType() << " on endpoint " << endpoint->getAddress();
return LIBUSB_ERROR_OTHER;
}
if (sts < 0) {
std::string strerr = libusb_error_name(sts);
LOG(WARNING) << "bulk_transfer returned error, endpoint: 0x" << std::hex << int(endpoint->getAddress()) << std::dec
<< ", error: " << strerr << ", err. num: " << static_cast<int>(sts);
return sts;
}
transferred = actual_length;
return LIBUSB_SUCCESS;
}
int UsbMessenger::reset_endpoint(const SeUsbEndpoint &endpoint, uint32_t timeout_ms) {
int ep = endpoint->getAddress();
auto sts = libusb_clear_halt(handle_->get(), ep);
if (sts < 0) {
std::string strerr = libusb_error_name(sts);
LOG(WARNING) << "reset_endpoint returned error, index: " << ep << ", error: " << strerr << ", number: "
<< static_cast<int>(sts);
return sts;
}
return LIBUSB_SUCCESS;
}
} // namespace platform
} // namespace libsmartereye2
|
sgallon-rin/miniprogram-sign-in
|
component/component-thirdPage/component-thirdPage.js
|
// component/component-thirdPage/component-thirdPage.js
const app = getApp()
Component({
/**
* 组件的属性列表
*/
properties: {
},
attached: function(){
console.log(app.globalData)
if (app.globalData.userInfo) {
this.setData({
userInfo: app.globalData.userInfo,
hasUserInfo: true
})
} else if (this.data.canIUse){
// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
app.userInfoReadyCallback = res => {
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
} else {
// 在没有 open-type=getUserInfo 版本的兼容处理
wx.getUserInfo({
success: res => {
app.globalData.userInfo = res.userInfo
this.setData({
userInfo: res.userInfo,
hasUserInfo: true
})
}
})
}
},
/**
* 组件的初始数据
*/
data: {
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo'),
iconImage: [
{
"src":"/icon/calendar.svg",
"alt":"calendar.svg",
"bind":"goToCalendar",
"text":"签到日历"
},
{
"src": "/icon/pie_chart__monochromatic.svg",
"alt": "pie_chart__monochromatic.svg",
"text": "数据汇总"
},
{
"src": "/icon/online_lesson.svg",
"alt": "online_lesson.svg",
"text": "在线课程"
},
{
"src": "/icon/scrum_board.svg",
"alt": "/icon/scrum_board.svg",
"text": "学校公告"
},
{
"src": "/icon/construction_worker.svg",
"alt": "/icon/construction.svg",
"text": "就业信息"
},
{
"src": "/icon/couple.svg",
"alt": "/icon/couple.svg",
"text": "我的课友"
},
]},
/**
* 组件的方法列表
*/
methods: {
goToCalendar: function(){
console.log("goToCalendar")
wx.navigateTo({
url: 'calander/calander',
})
},
getUserInfo: function(e) {
console.log(e)
app.globalData.userInfo = e.detail.userInfo
this.setData({
userInfo: e.detail.userInfo,
hasUserInfo: true
})
}
}
})
|
Sopra20-03/project-client
|
src/components/shared/models/Game.js
|
/**
* Game model
*/
class Game {
constructor(data = {}) {
this.gameId = null;
this.gameName = null;
this.creatorUsername = null;
this.dateCreated = null;
this.rounds = null;
this.playerCount = null;
this.currentRound = null;
this.score = null;
this.status = null;
this.mode=null;
//this.token = null;
Object.assign(this, data);
}
}
export default Game;
|
madnight/gitter
|
server/api/v1/rooms/bans.js
|
<reponame>madnight/gitter
"use strict";
var roomService = require('../../../services/room-service');
var restSerializer = require("../../../serializers/rest-serializer");
var loadTroupeFromParam = require('./load-troupe-param');
var RoomWithPolicyService = require('../../../services/room-with-policy-service');
module.exports = {
id: 'troupeBan',
index: function(req) {
return loadTroupeFromParam(req)
.then(function(troupe) {
var strategy = new restSerializer.TroupeBanStrategy({ });
return restSerializer.serialize(troupe.bans, strategy);
});
},
create: function(req, res) {
return loadTroupeFromParam(req)
.then(function(troupe) {
var roomWithPolicyService = new RoomWithPolicyService(troupe, req.user, req.userRoomPolicy);
var username = req.body.username;
var removeMessages = !!req.body.removeMessages;
return roomWithPolicyService.banUserFromRoom(username, { removeMessages: removeMessages });
})
.then(function(ban) {
if (!ban) {
res.status(202);
return {
removed: true
};
}
var strategy = new restSerializer.TroupeBanStrategy({ });
return restSerializer.serializeObject(ban, strategy);
});
},
show: function(req) {
var strategy = new restSerializer.TroupeBanStrategy({ });
return restSerializer.serializeObject(req.troupeBan, strategy);
},
destroy: function(req) {
return loadTroupeFromParam(req)
.then(function(troupe) {
var roomWithPolicyService = new RoomWithPolicyService(troupe, req.user, req.userRoomPolicy);
return roomWithPolicyService.unbanUserFromRoom(req.troupeBan.userId);
})
.then(function() {
return { success: true };
});
},
load: function(req, id) {
return roomService.findBanByUsername(req.params.troupeId, id);
}
};
|
arv/atom-traceur-test
|
build/runtime/system-map.js
|
"use strict";
function prefixMatchLength(name, prefix) {
var prefixParts = prefix.split('/');
var nameParts = name.split('/');
if (prefixParts.length > nameParts.length)
return 0;
for (var i = 0; i < prefixParts.length; i++) {
if (nameParts[i] != prefixParts[i])
return 0;
}
return prefixParts.length;
}
function applyMap(map, name, parentName) {
var curMatch,
curMatchLength = 0;
var curParent,
curParentMatchLength = 0;
if (parentName) {
var mappedName;
Object.getOwnPropertyNames(map).some(function(p) {
var curMap = map[p];
if (curMap && typeof curMap === 'object') {
if (prefixMatchLength(parentName, p) <= curParentMatchLength)
return;
Object.getOwnPropertyNames(curMap).forEach(function(q) {
if (prefixMatchLength(name, q) > curMatchLength) {
curMatch = q;
curMatchLength = q.split('/').length;
curParent = p;
curParentMatchLength = p.split('/').length;
}
});
}
if (curMatch) {
var subPath = name.split('/').splice(curMatchLength).join('/');
mappedName = map[curParent][curMatch] + (subPath ? '/' + subPath : '');
return mappedName;
}
});
}
if (mappedName)
return mappedName;
Object.getOwnPropertyNames(map).forEach(function(p) {
var curMap = map[p];
if (curMap && typeof curMap === 'string') {
if (prefixMatchLength(name, p) > curMatchLength) {
curMatch = p;
curMatchLength = p.split('/').length;
}
}
});
if (!curMatch)
return name;
var subPath = name.split('/').splice(curMatchLength).join('/');
return map[curMatch] + (subPath ? '/' + subPath : '');
}
var systemjs = {applyMap: applyMap};
Object.defineProperties(module.exports, {
systemjs: {get: function() {
return systemjs;
}},
__esModule: {value: true}
});
|
Apocrypse/LeetCode
|
Python/111minimum_depth_of_binary_tree.py
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if not root.left:
return 1+self.minDepth(root.right)
if not root.right:
return 1+self.minDepth(root.left)
return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
|
skkuse-adv/2019Fall_team2
|
analysis/reverse-engineering/decompile-fitts-20191031-2200/sources/kr/co/popone/fitts/ui/ImageViewForList.java
|
package kr.co.popone.fitts.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import androidx.appcompat.widget.AppCompatImageView;
import java.util.HashMap;
import kotlin.jvm.internal.Intrinsics;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public final class ImageViewForList extends AppCompatImageView {
private HashMap _$_findViewCache;
@Nullable
private Object extraData;
public void _$_clearFindViewByIdCache() {
HashMap hashMap = this._$_findViewCache;
if (hashMap != null) {
hashMap.clear();
}
}
public View _$_findCachedViewById(int i) {
if (this._$_findViewCache == null) {
this._$_findViewCache = new HashMap();
}
View view = (View) this._$_findViewCache.get(Integer.valueOf(i));
if (view != null) {
return view;
}
View findViewById = findViewById(i);
this._$_findViewCache.put(Integer.valueOf(i), findViewById);
return findViewById;
}
@Nullable
public final Object getExtraData() {
return this.extraData;
}
public final void setExtraData(@Nullable Object obj) {
this.extraData = obj;
}
public ImageViewForList(@NotNull Context context) {
Intrinsics.checkParameterIsNotNull(context, "context");
this(context, null);
}
public ImageViewForList(@NotNull Context context, @Nullable AttributeSet attributeSet) {
Intrinsics.checkParameterIsNotNull(context, "context");
this(context, attributeSet, 0);
}
public ImageViewForList(@NotNull Context context, @Nullable AttributeSet attributeSet, int i) {
Intrinsics.checkParameterIsNotNull(context, "context");
super(context, attributeSet, i);
}
}
|
teachy/blog
|
blog-common/src/main/java/club/javafan/blog/common/util/PageQueryUtil.java
|
package club.javafan.blog.common.util;
import java.util.HashMap;
/**
* @author 币圈豆子哥
* @date 2019/12/11 21:38
* @desc 分页插件实体
*/
public class PageQueryUtil extends HashMap<String, Object> {
//当前页码
private int page;
//每页条数
private int limit;
public PageQueryUtil(int page,int limit) {
this.page = page;
this.limit = limit;
this.put("start", (page - 1) * limit);
this.put("page", page);
this.put("limit", limit);
}
public PageQueryUtil(){};
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
@Override
public String toString() {
return "PageUtil{" +
"page=" + page +
", limit=" + limit +
'}';
}
}
|
nobo728x/logbook
|
logbook-core/src/main/java/org/zalando/logbook/Stages.java
|
<gh_stars>1000+
package org.zalando.logbook;
import org.zalando.logbook.Logbook.RequestWritingStage;
import static org.zalando.logbook.Logbook.ResponseProcessingStage;
import static org.zalando.logbook.Logbook.ResponseWritingStage;
final class Stages {
private Stages() {
}
static RequestWritingStage noop() {
return NoopRequestWriting.INSTANCE;
}
private enum NoopRequestWriting implements RequestWritingStage, Noop {
INSTANCE;
@Override
public ResponseProcessingStage write() {
return NoopResponseProcessing.INSTANCE;
}
}
private enum NoopResponseProcessing implements Noop {
INSTANCE
}
private interface Noop extends ResponseProcessingStage {
@Override
default ResponseWritingStage process(final HttpResponse response) {
return NoopResponseWriting.INSTANCE;
}
}
private enum NoopResponseWriting implements ResponseWritingStage {
INSTANCE;
@Override
public void write() {
// nothing to do here
}
}
}
|
stoogoff/python-to-javascript
|
PythonToJavascript/fixers/fixIndents.py
|
from helpers import gatherSubNodesD, getNodeKind
import re
def fixIndents( nodes ):
prefix = ""
for sub_node in gatherSubNodesD( nodes ):
if getNodeKind( sub_node ) == "DEDENT":
space_rgx = re.compile( r"(.*?)( +)(\n*)$", re.S )
m = space_rgx.match( sub_node.prefix )
if m:
prefix = m.group( 2 )
sub_node.prefix = m.group( 1 ) + m.group( 3 )
elif getNodeKind( sub_node ) == "NAME":
if prefix:
sub_node.prefix = " " * len( prefix )
prefix = ""
|
rodfernandez/lazojs
|
lib/public/bundle.js
|
define(['underscore', 'base', 'resolver/component', 'jquery'], function (_, Base, cmpResolver, $) {
'use strict';
var supportsImports = (function () {
return LAZO.isClient && 'import' in document.createElement('link');
})();
return Base.extend({
response: function (route, uri, options) {
options.success(null);
},
getLibPath: function () {
return LAZO.conf.libPath;
},
resolveBundleUrl: function (bundle) {
return bundle;
},
getComponentDef: function (route) {
return cmpResolver.getDef(route);
},
getComponentCss: function (name) {
return cmpResolver.getLinks(name, 'css');
},
// TODO: deprecate next major
getComponentCSS: function (name) {
return cmpResolver.getLinks(name, 'css');
},
getComponentImports: function (name) {
return cmpResolver.getLinks(name, 'import');
},
sortCss: function (links) {
return links;
},
sortImports: function (links) {
return links;
},
resolveImport: function (relativePath, namespace) {
if (LAZO.app.isServer) {
LAZO.logger.warn('bundle.resolveImport', 'Cannot call on server.');
return null;
}
var path = namespace === 'application' ? relativePath :
'components/' + namespace + '/imports/' + relativePath;
var $import = $('link[href*="' + path + '"][lazo-link-ctx="' + namespace + '"]');
var linkNode = $import[0];
return linkNode ? (supportsImports ? linkNode.import : linkNode) : null;
},
_createLink: function (link, defaults) {
if (_.isString(link)) {
return _.extend({ href: link }, defaults);
} else {
return _.extend(defaults, link);
}
},
_createCSSLink: function (link) {
return this._createLink(link, {
rel: 'stylesheet',
type: 'text/css',
'lazo-link': 'css',
'lazo-link-ctx': 'application'
});
},
_createCSSLinks: function (links) {
return _.map(links, _.bind(this._createCSSLink, this));
},
_createImportLink: function (link) {
return this._createLink(link, {
rel: 'import',
'lazo-link': 'import',
'lazo-link-ctx': 'application'
});
},
_createImportLinks: function (links) {
return _.map(links, _.bind(this._createImportLink, this));
}
});
});
|
NCIP/c3pr
|
codebase/projects/web/src/java/edu/duke/cabig/c3pr/web/participant/ParticipantDetailsTab.java
|
<gh_stars>1-10
/*******************************************************************************
* Copyright Duke Comprehensive Cancer Center and SemanticBits
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/c3pr/LICENSE.txt for details.
******************************************************************************/
package edu.duke.cabig.c3pr.web.participant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.validation.Errors;
import edu.duke.cabig.c3pr.constants.FamilialRelationshipName;
import edu.duke.cabig.c3pr.constants.RaceCodeEnum;
import edu.duke.cabig.c3pr.constants.RelationshipCategory;
import edu.duke.cabig.c3pr.domain.Participant;
import edu.duke.cabig.c3pr.domain.RaceCodeAssociation;
import edu.duke.cabig.c3pr.domain.validator.ParticipantValidator;
import edu.duke.cabig.c3pr.service.PersonnelService;
import edu.duke.cabig.c3pr.utils.Lov;
import edu.duke.cabig.c3pr.utils.web.WebUtils;
import edu.duke.cabig.c3pr.web.RaceCodeHolder;
public class ParticipantDetailsTab extends ParticipantTab {
private ParticipantValidator participantValidator;
private PersonnelService personnelService;
public void setPersonnelService(PersonnelService personnelService) {
this.personnelService = personnelService;
}
public ParticipantDetailsTab() {
super("Details", "Details", "participant/participant");
setShowSummary("false");
}
@SuppressWarnings("unchecked")
@Override
public Map<String, Object> referenceData(HttpServletRequest request, ParticipantWrapper command) {
if(request.getParameter("fromCreateRegistration")!=null && request.getParameter("fromCreateRegistration").equals("true")){
request.getSession().setAttribute("fromCreateRegistration", true);
if(request.getParameter("studySiteStudyVersionIdFromCreateReg")!=null && !request.getParameter("studySiteStudyVersionIdFromCreateReg").equals("")){
request.getSession().setAttribute("studySiteStudyVersionIdFromCreateReg", request.getParameter("studySiteStudyVersionIdFromCreateReg"));
} else if(request.getParameter("searchedForStudy").equals("true")){
request.getSession().setAttribute("searchedForStudy", request.getParameter("searchedForStudy"));
request.getSession().setAttribute("studySearchType", request.getParameter("studySearchType"));
request.getSession().setAttribute("studySearchText", request.getParameter("studySearchText"));
}
}
Map<String, List<Lov>> configMap = configurationProperty.getMap();
Map<String, Object> refdata = new HashMap<String, Object>();
refdata.put("administrativeGenderCode", configMap.get("administrativeGenderCode"));
refdata.put("ethnicGroupCode", configMap.get("ethnicGroupCode"));
refdata.put("searchTypeRefData", configMap.get("participantSearchType"));
List<Lov> sysParticipantIdentifiersType = new ArrayList<Lov>();
// remove Household Identifier type from sysIdentifiers as it should be included only as a part of organization identifiers
for(Lov partOrgIdType : configMap.get("participantIdentifiersType")){
if(!partOrgIdType.getCode().equalsIgnoreCase("HOUSEHOLD_IDENTIFIER")){
sysParticipantIdentifiersType.add(partOrgIdType);
}
}
refdata.put("orgIdentifiersTypeRefData", configMap.get("participantIdentifiersType"));
refdata.put("sysIdentifiersTypeRefData", sysParticipantIdentifiersType);
refdata.put("mandatory", "true");
refdata.put("raceCodes", WebUtils.collectOptions(RaceCodeEnum.values()));
List<Lov> familialRelationshipNames = new ArrayList<Lov>();
Lov lov = new Lov();
for(FamilialRelationshipName familialRelationship : FamilialRelationshipName.values()){
lov = new Lov();
lov.setCode(familialRelationship.getName());
lov.setDesc(familialRelationship.getCode());
familialRelationshipNames.add(lov);
}
refdata.put("familialRelationshipNames",familialRelationshipNames);
Participant participant = command.getParticipant();
for(Object object : WebUtils.collectOptions(RaceCodeEnum.values())){
RaceCodeEnum raceCode = (RaceCodeEnum) object ;
RaceCodeHolder holder = new RaceCodeHolder();
if(participant.getRaceCodes().contains(raceCode)){
holder.setRaceCode(raceCode);
}else{
holder.setRaceCode(null);
}
command.addRaceCodeHolder(holder);
}
return refdata;
}
@Override
public void validate(ParticipantWrapper participantWrapper, Errors errors) {
super.validate(participantWrapper, errors);
participantValidator.validateParticipantFamilialRelationships(participantWrapper.getParticipant(), errors);
participantValidator.validateIdentifiers(participantWrapper.getParticipant(), errors);
}
public ParticipantValidator getParticipantValidator() {
return participantValidator;
}
public void setParticipantValidator(ParticipantValidator participantValidator) {
this.participantValidator = participantValidator;
}
@Override
public void postProcess(HttpServletRequest request, ParticipantWrapper command, Errors errors) {
Participant participant = command.getParticipant();
for(RaceCodeEnum raceCode : command.getRaceCodesFromHolder()){
if(!participant.getRaceCodes().contains(raceCode)){
RaceCodeAssociation raceCodeAssociation = new RaceCodeAssociation();
raceCodeAssociation.setRaceCode(raceCode);
participant.addRaceCodeAssociation(raceCodeAssociation);
}
}
for(RaceCodeEnum raceCode : participant.getRaceCodes()){
if(!command.getRaceCodesFromHolder().contains(raceCode)){
participant.removeRaceCodeAssociation(participant.getRaceCodeAssociation(raceCode));
}
}
if(command.getParticipant().getId() == null){
gov.nih.nci.security.authorization.domainobjects.User user = (gov.nih.nci.security.authorization.domainobjects.User) request
.getSession().getAttribute("userObject");
command.getParticipant().getHealthcareSites().addAll(personnelService.getUserOrganizations(user));
}
}
}
|
mcodegeeks/OpenKODE-Framework
|
01_Develop/libXMFFmpeg/Source/libavcodec/srtdec_c.cpp
|
<filename>01_Develop/libXMFFmpeg/Source/libavcodec/srtdec_c.cpp
/*
* SubRip subtitle decoder
* Copyright (c) 2010 <NAME> <<EMAIL>>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "XMFFmpeg/libavutil/avstring.h"
#include "XMFFmpeg/libavutil/parseutils.h"
#include "internal.h"
#include "ass.h"
static int html_color_parse(AVCodecContext *avctx, const char *str)
{
uint8_t rgba[4];
if (av_parse_color(rgba, str, strcspn(str, "\" >"), avctx) < 0)
return -1;
return rgba[0] | rgba[1] << 8 | rgba[2] << 16;
}
enum {
PARAM_UNKNOWN = -1,
PARAM_SIZE,
PARAM_COLOR,
PARAM_FACE,
PARAM_NUMBER
};
typedef struct {
char tag[128];
char param[PARAM_NUMBER][128];
} SrtStack;
static const char *srt_to_ass(AVCodecContext *avctx, char *out, char *out_end,
const char *in, int x1, int y1, int x2, int y2)
{
char c, *param, buffer[128], tmp[128];
int len, tag_close, sptr = 1, line_start = 1, an = 0, end = 0;
SrtStack stack[16];
stack[0].tag[0] = 0;
strcpy(stack[0].param[PARAM_SIZE], "{\\fs}");
strcpy(stack[0].param[PARAM_COLOR], "{\\c}");
strcpy(stack[0].param[PARAM_FACE], "{\\fn}");
if (x1 >= 0 && y1 >= 0) {
if (x2 >= 0 && y2 >= 0 && (x2 != x1 || y2 != y1))
out += snprintf(out, out_end-out,
"{\\an1}{\\move(%d,%d,%d,%d)}", x1, y1, x2, y2);
else
out += snprintf(out, out_end-out, "{\\an1}{\\pos(%d,%d)}", x1, y1);
}
for (; out < out_end && !end && *in; in++) {
switch (*in) {
case '\r':
break;
case '\n':
if (line_start) {
end = 1;
break;
}
while (out[-1] == ' ')
out--;
out += snprintf(out, out_end-out, "\\N");
line_start = 1;
break;
case ' ':
if (!line_start)
*out++ = *in;
break;
case '{': /* skip all {\xxx} substrings except for {\an%d}
and all microdvd like styles such as {Y:xxx} */
an += sscanf(in, "{\\an%*1u}%c", &c) == 1;
if ((an != 1 && sscanf(in, "{\\%*[^}]}%n%c", &len, &c) > 0) ||
sscanf(in, "{%*1[CcFfoPSsYy]:%*[^}]}%n%c", &len, &c) > 0) {
in += len - 1;
} else
*out++ = *in;
break;
case '<':
tag_close = in[1] == '/';
if (sscanf(in+tag_close+1, "%127[^>]>%n%c", buffer, &len,&c) >= 2) {
if ((param = strchr(buffer, ' ')))
*param++ = 0;
if ((!tag_close && sptr < FF_ARRAY_ELEMS(stack)) ||
( tag_close && sptr > 0 && !strcmp(stack[sptr-1].tag, buffer))) {
int i, j, unknown = 0;
in += len + tag_close;
if (!tag_close)
memset(stack+sptr, 0, sizeof(*stack));
if (!strcmp(buffer, "font")) {
if (tag_close) {
for (i=PARAM_NUMBER-1; i>=0; i--)
if (stack[sptr-1].param[i][0])
for (j=sptr-2; j>=0; j--)
if (stack[j].param[i][0]) {
out += snprintf(out, out_end-out,
"%s", stack[j].param[i]);
break;
}
} else {
while (param) {
if (!strncmp(param, "size=", 5)) {
unsigned font_size;
param += 5 + (param[5] == '"');
if (sscanf(param, "%u", &font_size) == 1) {
snprintf(stack[sptr].param[PARAM_SIZE],
sizeof(stack[0].param[PARAM_SIZE]),
"{\\fs%u}", font_size);
}
} else if (!strncmp(param, "color=", 6)) {
param += 6 + (param[6] == '"');
snprintf(stack[sptr].param[PARAM_COLOR],
sizeof(stack[0].param[PARAM_COLOR]),
"{\\c&H%X&}",
html_color_parse(avctx, param));
} else if (!strncmp(param, "face=", 5)) {
param += 5 + (param[5] == '"');
len = strcspn(param,
param[-1] == '"' ? "\"" :" ");
av_strlcpy(tmp, param,
FFMIN(sizeof(tmp), len+1));
param += len;
snprintf(stack[sptr].param[PARAM_FACE],
sizeof(stack[0].param[PARAM_FACE]),
"{\\fn%s}", tmp);
}
if ((param = strchr(param, ' ')))
param++;
}
for (i=0; i<PARAM_NUMBER; i++)
if (stack[sptr].param[i][0])
out += snprintf(out, out_end-out,
"%s", stack[sptr].param[i]);
}
} else if (!buffer[1] && strspn(buffer, "bisu") == 1) {
out += snprintf(out, out_end-out,
"{\\%c%d}", buffer[0], !tag_close);
} else {
unknown = 1;
snprintf(tmp, sizeof(tmp), "</%s>", buffer);
}
if (tag_close) {
sptr--;
} else if (unknown && !strstr(in, tmp)) {
in -= len + tag_close;
*out++ = *in;
} else
av_strlcpy(stack[sptr++].tag, buffer,
sizeof(stack[0].tag));
break;
}
}
default:
*out++ = *in;
break;
}
if (*in != ' ' && *in != '\r' && *in != '\n')
line_start = 0;
}
out = FFMIN(out, out_end-3);
while (!strncmp(out-2, "\\N", 2))
out -= 2;
while (out[-1] == ' ')
out--;
out += snprintf(out, out_end-out, "\r\n");
return in;
}
static const char *read_ts(const char *buf, int *ts_start, int *ts_end,
int *x1, int *y1, int *x2, int *y2)
{
int i, hs, ms, ss, he, me, se;
for (i=0; i<2; i++) {
/* try to read timestamps in either the first or second line */
int c = sscanf(buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d"
"%*[ ]X1:%u X2:%u Y1:%u Y2:%u",
&hs, &ms, &ss, ts_start, &he, &me, &se, ts_end,
x1, x2, y1, y2);
buf += strcspn(buf, "\n") + 1;
if (c >= 8) {
*ts_start = 100*(ss + 60*(ms + 60*hs)) + *ts_start/10;
*ts_end = 100*(se + 60*(me + 60*he)) + *ts_end /10;
return buf;
}
}
return NULL;
}
static int srt_decode_frame(AVCodecContext *avctx,
void *data, int *got_sub_ptr, AVPacket *avpkt)
{
AVSubtitle *sub = (AVSubtitle *)data;
int ts_start, ts_end, x1 = -1, y1 = -1, x2 = -1, y2 = -1;
char buffer[2048];
const char *ptr = (const char *)avpkt->data;
const char *end = (const char *)(avpkt->data + avpkt->size);
if (avpkt->size <= 0)
return avpkt->size;
while (ptr < end && *ptr) {
ptr = read_ts(ptr, &ts_start, &ts_end, &x1, &y1, &x2, &y2);
if (!ptr)
break;
ptr = srt_to_ass(avctx, buffer, buffer+sizeof(buffer), ptr,
x1, y1, x2, y2);
ff_ass_add_rect(sub, buffer, ts_start, ts_end, 0);
}
*got_sub_ptr = sub->num_rects > 0;
return avpkt->size;
}
AVCodec ff_srt_decoder = {
/*.name = */ "srt",
/*.type = */ AVMEDIA_TYPE_SUBTITLE,
/*.id = */ CODEC_ID_SRT,
/*.priv_data_size = */ 0,
/*.init = */ ff_ass_subtitle_header_default,
/*.encode = */ 0,
/*.close = */ 0,
/*.decode = */ srt_decode_frame,
/*.capabilities = */ 0,
/*.next = */ 0,
/*.flush = */ 0,
/*.supported_framerates = */ 0,
/*.pix_fmts = */ 0,
/*.long_name = */ NULL_IF_CONFIG_SMALL("SubRip subtitle"),
};
|
vidit1999/daily_coding_problem
|
data/dailyCodingProblem795.cpp
|
#include <bits/stdc++.h>
using namespace std;
/*
Assume you have access to a function toss_biased() which
returns 0 or 1 with a probability that's not 50-50
(but also not 0-100 or 100-0). You do not know the bias of the coin.
Write a function to simulate an unbiased coin toss.
*/
// true => head (70%)
// false => tail (30%)
bool biasedCoin(){
return float(rand())/float(RAND_MAX) >= 0.3;
}
// true => head (50%)
// false => tail (50%)
bool unbiasedCoin(){
bool toss1, toss2;
do{
toss1 = biasedCoin();
toss2 = biasedCoin();
}while(!(toss1 ^ toss2));
return toss1;
}
pair<int, int> testFunc(){
int true_count = 0, false_count = 0;
for(int i=0; i<1000; i++){
if(unbiasedCoin()) true_count++;
else false_count++;
}
return {true_count, false_count};
}
// main function
int main(){
srand(time(0));
for(int i=0; i<5; i++){
auto ans = testFunc();
cout << ans.first << ", " << ans.second << "\n";
}
return 0;
}
|
AAU-PSix/canary
|
src/instrumentor/c_tree_infestator.py
|
from typing import List, Dict, Callable
from ts import (
Node,
Parser,
Tree,
CSyntax,
CNodeType,
CField
)
from cfa import (
CFA,
CFANode
)
from .c_canary_factory import CCanaryFactory
from .tree_infection import TreeInfection
from .tree_infestator import TreeInfestator
class CTreeInfestator(TreeInfestator):
def __init__(self, parser: Parser, canary_factory: CCanaryFactory) -> None:
self._parser = parser
self._canary_factory = canary_factory
self._syntax = CSyntax()
super().__init__()
def nests_of_if_condition(self, condition: Node) -> List[Node]:
# The parent of the condition is the "if_statement" itself.
return [ condition.parent ]
def nests_of_while_condition(self, condition: Node) -> List[Node]:
# We take the parent because the node for a "while"-loop
# will always be of type "parenthesized_expression"
# as the immediate "child" of the "while_statement"
return [ condition.parent ]
def nests_of_do_while_condition(self, condition: Node) -> List[Node]:
# We take the parent because the node for a "do while"-loop
# will always be of type "parenthesized_expression"
# as the immediate "child" of the "while_statement"
return [ condition.parent ]
def nests_of_for_loop_body(self, body: Node) -> List[Node]:
return [ body.get_immediate_descendent_of_types(
[ CNodeType.FOR_STATEMENT.value ]
) ]
def nests_of_case_value_for_switch(self, condition: Node) -> List[Node]:
# The parent of a switch condition is the condition itself
return [ condition.parent ]
def nests_of_labeled_statement(self, label: Node) -> List[Node]:
return [ label, label.named_children[1] ]
def nests_of_expression_statement(self, expression_stmt: Node) -> List[Node]:
return [ expression_stmt ]
def nests_of_return_statement(self, return_stmt: Node) -> List[Node]:
return [ return_stmt ]
def nests_of_declaration(self, declaration: Node) -> List[Node]:
return [ declaration ]
def nests_of_function_definition(self, descendent: Node) -> List[Node]:
# descendent is a descendent of the "function_definition"
function_definition = descendent.get_descendent_of_types([ CNodeType.FUNCTION_DEFINITION.value ])
return [ function_definition ]
def nests_of_translation_unit(self, translation_unit: Node) -> List[Node]:
return [ translation_unit ]
def nests_of_goto_statement(self, goto_statement: Node) -> List[Node]:
return [ goto_statement ]
def nests(self, cfa: CFA[CFANode]) -> List[Node]:
nests: List[Node] = list()
ascendent = cfa.root.node.get_immediate_descendent_of_types(
[ CNodeType.FUNCTION_DEFINITION.value, CNodeType.TRANSLATION_UNIT.value ]
)
if ascendent.is_type(CNodeType.TRANSLATION_UNIT):
nests.extend(self.nests_of_translation_unit(ascendent))
for cfa_node in cfa.nodes:
node: Node = cfa_node.node
# Case 1: if-statements (Including "else if" and "else")
if self._syntax.is_condition_of_if(node):
nests.extend(self.nests_of_if_condition(node))
# Case 2: while-loops
if self._syntax.is_condition_of_while(node):
nests.extend(self.nests_of_while_condition(node))
# Case 3: do-while-loops
if self._syntax.is_condition_of_do_while(node):
nests.extend(self.nests_of_do_while_condition(node))
# Case 4: for-loop
# Since a for-loop can exist without a "init", "cond", and "update"
# The only persistent aspect of it is the body, which is always included.
if self._syntax.is_body_of_for_loop(node):
nests.extend(self.nests_of_for_loop_body(node))
# Case 5: Switch (Cases and default)
if self._syntax.is_condition_of_switch(node):
nests.extend(self.nests_of_case_value_for_switch(node))
# Case 6: Labels
if self._syntax.is_labeled_statement(node):
nests.extend(self.nests_of_labeled_statement(node))
# Case 7: Expression statement
if self._syntax.is_expression_statement(node):
nests.extend(self.nests_of_expression_statement(node))
# Case 8: Declaration
if self._syntax.is_declaration(node):
# TODO: Declarations nests should not be added,
# if they are the intiialization of a for-loop.
nests.extend(self.nests_of_declaration(node))
# Case 9: Return statement
if self._syntax.is_return_statement(node):
nests.extend(self.nests_of_return_statement(node))
# Case 10: Goto
if self._syntax.is_goto_statement(node):
nests.extend(self.nests_of_goto_statement(node))
# Case 1: First function definition (Begin/end unit)
if self._syntax.is_immediate_of_function_definition(node):
nests.extend(self.nests_of_function_definition(node))
# Remove duplicates
corrected: List[Node] = list()
for nest in nests:
if nest not in corrected:
corrected.append(nest)
return corrected
def infection_spore_expression_statement(self, _: Node) -> List[TreeInfection]:
return [ ]
def infection_spore_assignment_statement(self, _: Node) -> List[TreeInfection]:
return [ ]
def infection_spore_return_statement(self, _: Node) -> List[TreeInfection]:
return [ ]
def infection_spore_declaration(self, _: Node) -> List[TreeInfection]:
return [ ]
def infection_spore_if_statement(self, if_stmt: Node) -> List[TreeInfection]:
infections: List[TreeInfection] = [ ]
consequence: Node = if_stmt.child_by_field(CField.CONSEQUENCE)
alternative: Node = if_stmt.child_by_field(CField.ALTERNATIVE)
consequence_postfix: str = ""
alternative_postfix: str = ""
if alternative is None:
consequence_postfix = self._canary_factory.create_location_tweet()
elif not self._syntax.has_else_if(if_stmt):
alternative_postfix = self._canary_factory.create_location_tweet()
# We dont have to check if "consequence" is None, because every
# "if_statement" has a consequence of its "condition"
infections.extend(self._canary_factory.create_location_tweets(
consequence,
pre_infix=self._canary_factory.create_location_tweet(),
postfix=consequence_postfix
))
# If it is an "else if", then it is handled as a seperate "if"
if alternative is not None and not self._syntax.has_else_if(if_stmt):
infections.extend(self._canary_factory.create_location_tweets(
alternative,
pre_infix=self._canary_factory.create_location_tweet(),
postfix=alternative_postfix
))
return infections
def infection_spore_while_statement(self, while_stmt: Node) -> List[TreeInfection]:
body: Node = while_stmt.child_by_field(CField.BODY)
infections: List[TreeInfection] = self._canary_factory.create_location_tweets(
body,
pre_infix=self._canary_factory.create_location_tweet(),
postfix=self._canary_factory.create_location_tweet()
)
return infections
def infection_spore_do_statement(self, do_stmt: Node) -> List[TreeInfection]:
body: Node = do_stmt.child_by_field(CField.BODY)
infections: List[TreeInfection] = self._canary_factory.create_location_tweets(
body,
pre_infix=self._canary_factory.create_location_tweet(),
)
infections.append(
self._canary_factory.append_location_tweet(do_stmt)
)
return infections
def infection_spore_for_statement(self, for_stmt: Node) -> List[TreeInfection]:
body: Node = self._syntax.get_for_loop_body(for_stmt)
# If it is a expression statement then the body is just a ";"
# I.e. for(int i = 0; i < 10; ++i);
# I.e. for(int i = 0; i < 10; ++i) {TWEET();;TWEET()}
return self._canary_factory.create_location_tweets(
body,
pre_infix=self._canary_factory.create_location_tweet(),
postfix=self._canary_factory.create_location_tweet(),
)
def infection_spore_switch_statement(self, switch_stmt: Node) -> List[TreeInfection]:
infections: List[TreeInfection] = [ ]
body: Node = switch_stmt.child_by_field(CField.BODY)
for case in body.named_children:
is_default: bool = self._syntax.is_default_switch_case(case)
if is_default:
infections.append(
# The second (index 1) child is the ":" character for default cases
self._canary_factory.append_location_tweet(case.children[1])
)
else:
infections.append(
# The second (index 1) child is the ":" character for normal cases
self._canary_factory.append_location_tweet(case.children[2])
)
infections.append(
self._canary_factory.append_location_tweet(switch_stmt)
)
return infections
def infection_spore_labeled_statement(self, node: Node) -> List[TreeInfection]:
# For a "labeled_statement" the second child (index 1) is the ":"
return [ self._canary_factory.append_location_tweet(node.children[1]) ]
def infection_spore_function_definition(self, node: Node) -> List[TreeInfection]:
body = node.child_by_field(CField.BODY)
left_paren = body.children[0]
return [
self._canary_factory.append_location_tweet(left_paren),
]
def infection_spore_goto_statement(self, node: Node) -> List[TreeInfection]:
return [ self._canary_factory.insert_location_tweet(node) ]
def infection_spore_translation_unit(self, node: Node) -> List[TreeInfection]:
return [ self._canary_factory.insert_location_tweet(node) ]
def infect(self, tree: Tree, cfa: CFA[CFANode]) -> Tree:
probes: Dict[str, Callable[[Node], List[TreeInfection]]] = {
# Sequential statements
CNodeType.EXPRESSION_STATEMENT.value: self.infection_spore_expression_statement,
CNodeType.ASSIGNMENT_EXPRESSION.value: self.infection_spore_expression_statement,
CNodeType.RETURN_STATEMENT.value: self.infection_spore_return_statement,
CNodeType.DECLARATION.value: self.infection_spore_declaration,
# Control structures
CNodeType.IF_STATEMENT.value: self.infection_spore_if_statement,
CNodeType.WHILE_STATEMENT.value: self.infection_spore_while_statement,
CNodeType.DO_STATEMENT.value: self.infection_spore_do_statement,
CNodeType.FOR_STATEMENT.value: self.infection_spore_for_statement,
CNodeType.SWITCH_STATEMENT.value: self.infection_spore_switch_statement,
# Unconditional jump
CNodeType.LABELED_STATEMENT.value: self.infection_spore_labeled_statement,
CNodeType.GOTO_STATEMENT.value: self.infection_spore_goto_statement,
# Additional
CNodeType.FUNCTION_DEFINITION.value: self.infection_spore_function_definition,
CNodeType.TRANSLATION_UNIT.value: self.infection_spore_translation_unit
}
# Step 1: Find the infections
infections: List[TreeInfection] = [ ]
for nest in self.nests(cfa):
if nest.type in probes:
infections.extend(probes[nest.type](nest))
# Step 2: Infect the tree from end to start
infections.sort(key=lambda x: x.last_byte_index, reverse=True)
for infection in infections:
tree = infection.do(self._parser, tree)
return tree
|
liasece/micserver
|
micserver.go
|
package micserver
import (
"math/rand"
"time"
"github.com/liasece/micserver/app"
"github.com/liasece/micserver/conf"
)
// SetupApp func
func SetupApp(configpath string) (*app.App, error) {
// 初始化随机数种子
rand.Seed(time.Now().UnixNano())
cfg, err := conf.LoadConfig(configpath)
if err != nil {
return nil, err
}
res := &app.App{}
res.Setup(cfg)
return res, nil
}
|
Willy5s/Pirates-Online-Rewritten
|
pirates/quest/QuestHolder.py
|
<gh_stars>10-100
from pirates.quest import QuestHolderBase
class QuestHolder(QuestHolderBase.QuestHolderBase):
def getLinkedHolders(self):
return []
|
ArrogantWombatics/openbsd-src
|
usr.sbin/amd/rpcx/amq_xdr.c
|
/*
* Please do not edit this file.
* It was generated using rpcgen.
*/
#include "amq.h"
bool_t
xdr_amq_string(XDR *xdrs, amq_string *objp)
{
if (!xdr_string(xdrs, objp, AMQ_STRLEN))
return (FALSE);
return (TRUE);
}
bool_t
xdr_time_type(XDR *xdrs, time_type *objp)
{
if (!xdr_int64_t(xdrs, objp))
return (FALSE);
return (TRUE);
}
bool_t
xdr_amq_mount_tree(XDR *xdrs, amq_mount_tree *objp)
{
if (!xdr_amq_string(xdrs, &objp->mt_mountinfo))
return (FALSE);
if (!xdr_amq_string(xdrs, &objp->mt_directory))
return (FALSE);
if (!xdr_amq_string(xdrs, &objp->mt_mountpoint))
return (FALSE);
if (!xdr_amq_string(xdrs, &objp->mt_type))
return (FALSE);
if (!xdr_time_type(xdrs, &objp->mt_mounttime))
return (FALSE);
if (!xdr_u_short(xdrs, &objp->mt_mountuid))
return (FALSE);
if (!xdr_int(xdrs, &objp->mt_getattr))
return (FALSE);
if (!xdr_int(xdrs, &objp->mt_lookup))
return (FALSE);
if (!xdr_int(xdrs, &objp->mt_readdir))
return (FALSE);
if (!xdr_int(xdrs, &objp->mt_readlink))
return (FALSE);
if (!xdr_int(xdrs, &objp->mt_statfs))
return (FALSE);
if (!xdr_pointer(xdrs, (char **)&objp->mt_next, sizeof(amq_mount_tree), (xdrproc_t)xdr_amq_mount_tree))
return (FALSE);
if (!xdr_pointer(xdrs, (char **)&objp->mt_child, sizeof(amq_mount_tree), (xdrproc_t)xdr_amq_mount_tree))
return (FALSE);
return (TRUE);
}
bool_t
xdr_amq_mount_tree_p(XDR *xdrs, amq_mount_tree_p *objp)
{
if (!xdr_pointer(xdrs, (char **)objp, sizeof(amq_mount_tree), (xdrproc_t)xdr_amq_mount_tree))
return (FALSE);
return (TRUE);
}
bool_t
xdr_amq_mount_info(XDR *xdrs, amq_mount_info *objp)
{
if (!xdr_amq_string(xdrs, &objp->mi_type))
return (FALSE);
if (!xdr_amq_string(xdrs, &objp->mi_mountpt))
return (FALSE);
if (!xdr_amq_string(xdrs, &objp->mi_mountinfo))
return (FALSE);
if (!xdr_amq_string(xdrs, &objp->mi_fserver))
return (FALSE);
if (!xdr_int(xdrs, &objp->mi_error))
return (FALSE);
if (!xdr_int(xdrs, &objp->mi_refc))
return (FALSE);
if (!xdr_int(xdrs, &objp->mi_up))
return (FALSE);
return (TRUE);
}
bool_t
xdr_amq_mount_info_list(XDR *xdrs, amq_mount_info_list *objp)
{
if (!xdr_array(xdrs, (char **)&objp->amq_mount_info_list_val,
(u_int *)&objp->amq_mount_info_list_len,
~0, sizeof(amq_mount_info), (xdrproc_t)xdr_amq_mount_info))
return (FALSE);
return (TRUE);
}
bool_t
xdr_amq_mount_tree_list(XDR *xdrs, amq_mount_tree_list *objp)
{
if (!xdr_array(xdrs, (char **)&objp->amq_mount_tree_list_val,
(u_int *)&objp->amq_mount_tree_list_len,
~0, sizeof(amq_mount_tree_p), (xdrproc_t)xdr_amq_mount_tree_p))
return (FALSE);
return (TRUE);
}
bool_t
xdr_amq_mount_stats(XDR *xdrs, amq_mount_stats *objp)
{
if (!xdr_int(xdrs, &objp->as_drops))
return (FALSE);
if (!xdr_int(xdrs, &objp->as_stale))
return (FALSE);
if (!xdr_int(xdrs, &objp->as_mok))
return (FALSE);
if (!xdr_int(xdrs, &objp->as_merr))
return (FALSE);
if (!xdr_int(xdrs, &objp->as_uerr))
return (FALSE);
return (TRUE);
}
bool_t
xdr_amq_opt(XDR *xdrs, amq_opt *objp)
{
if (!xdr_enum(xdrs, (enum_t *)objp))
return (FALSE);
return (TRUE);
}
bool_t
xdr_amq_setopt(XDR *xdrs, amq_setopt *objp)
{
if (!xdr_amq_opt(xdrs, &objp->as_opt))
return (FALSE);
if (!xdr_amq_string(xdrs, &objp->as_str))
return (FALSE);
return (TRUE);
}
|
ykyh1214/gadwords
|
draft.go
|
<gh_stars>0
package gadwords
type DraftService struct {
Auth
}
func NewDraftService(auth *Auth) *DraftService {
return &DraftService{Auth: *auth}
}
|
holdenhinkle/vets-website
|
src/applications/financial-status-report/pages/householdIncome/socialSecurity.js
|
<reponame>holdenhinkle/vets-website<filename>src/applications/financial-status-report/pages/householdIncome/socialSecurity.js<gh_stars>0
import currencyUI from 'platform/forms-system/src/js/definitions/currency';
import _ from 'lodash/fp';
export const uiSchema = {
'ui:title': 'Your other income',
additionalIncome: {
hasSocialSecurityPayments: {
'ui:title': 'Do you currently receive social security payments?',
'ui:widget': 'yesNo',
'ui:required': () => true,
},
socialSecurity: {
'ui:options': {
expandUnder: 'hasSocialSecurityPayments',
},
socialSecurityAmount: _.merge(
currencyUI('How much do you receive for Social Security each month?'),
{
'ui:options': {
widgetClassNames: 'input-size-3',
},
'ui:required': formData =>
formData.additionalIncome.hasSocialSecurityPayments,
},
),
},
},
};
export const schema = {
type: 'object',
properties: {
additionalIncome: {
type: 'object',
properties: {
hasSocialSecurityPayments: {
type: 'boolean',
},
socialSecurity: {
type: 'object',
properties: {
socialSecurityAmount: {
type: 'number',
},
},
},
},
},
},
};
|
iitsoftware/swiftmq-client
|
src/main/java/com/swiftmq/net/protocol/raw/RawOutputHandler.java
|
/*
* Copyright 2019 IIT Software GmbH
*
* IIT Software GmbH licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.swiftmq.net.protocol.raw;
import com.swiftmq.net.protocol.ProtocolOutputHandler;
/**
* A RawOutputHandler handles a raw byte stream and pass them to an output listener
* on every call to <code>flush()</code> without any protocol specifiy actions.
*
* @author IIT GmbH, Bremen/Germany, Copyright (c) 2000-2002, All Rights Reserved
*/
public class RawOutputHandler extends ProtocolOutputHandler {
final static int BUFFER_SIZE = 1024 * 128;
final static int EXTEND_SIZE = 1024 * 64;
int bufferSize = BUFFER_SIZE;
int extendSize = EXTEND_SIZE;
byte[] currentInput = null;
int inputLength = 0;
byte[] currentOutput = null;
int outputOffset = 0;
int outputLength = 0;
int chunkCount = 0;
public RawOutputHandler(int bufferSize, int extendSize) {
this.bufferSize = bufferSize;
this.extendSize = extendSize;
}
public RawOutputHandler() {
this(BUFFER_SIZE, EXTEND_SIZE);
}
private void ensureInput(int size) {
if (currentInput == null) {
currentInput = new byte[Math.max(bufferSize, size)];
inputLength = 0;
} else {
if (currentInput.length - inputLength < size) {
byte b[] = new byte[Math.max(extendSize, size + inputLength)];
System.arraycopy(currentInput, 0, b, 0, inputLength);
currentInput = b;
}
}
}
public ProtocolOutputHandler create() {
return new RawOutputHandler();
}
public ProtocolOutputHandler create(int bufferSize, int extendSize) {
return new RawOutputHandler(bufferSize, extendSize);
}
public int getChunkCount() {
return chunkCount;
}
protected byte[] getByteArray() {
if (currentOutput == null) {
currentOutput = currentInput;
outputOffset = 0;
outputLength = inputLength;
}
return currentOutput;
}
protected int getOffset() {
return outputOffset;
}
protected int getLength() {
return outputLength - outputOffset;
}
protected void setBytesWritten(int written) {
outputOffset += written;
if (outputOffset == outputLength) {
currentOutput = null;
outputOffset = 0;
outputLength = 0;
inputLength = 0;
chunkCount = 0;
}
}
protected void addByte(byte b) {
ensureInput(1);
currentInput[inputLength++] = b;
}
protected void addBytes(byte[] b, int offset, int len) {
ensureInput(len);
System.arraycopy(b, offset, currentInput, inputLength, len);
inputLength += len;
}
protected void markChunkCompleted() {
chunkCount = 1;
}
public String toString() {
return "[RawOutputHandler]";
}
}
|
qianfei11/zstack
|
sdk/src/main/java/org/zstack/sdk/DeleteEcsInstanceLocalResult.java
|
<reponame>qianfei11/zstack
package org.zstack.sdk;
public class DeleteEcsInstanceLocalResult {
}
|
flipk/pfkutils
|
libprotossl/libprotossl.h
|
/* -*- Mode:c++; eval:(c-set-style "BSD"); c-basic-offset:4; indent-tabs-mode:nil; tab-width:8 -*- */
#ifndef __LIBPROTOSSL2_H__
#define __LIBPROTOSSL2_H__
#include "pfkutils_config.h"
#include <mbedtls/entropy.h>
#include <mbedtls/ctr_drbg.h>
#include <mbedtls/ssl.h>
#include <mbedtls/ssl_cookie.h>
#include <mbedtls/timing.h>
#if HAVE_MBEDTLS_NET_H
#include <mbedtls/net.h>
#endif
#if HAVE_MBEDTLS_NET_SOCKETS_H
#include <mbedtls/net_sockets.h>
#endif
#include <mbedtls/error.h>
#include <mbedtls/debug.h>
#include <google/protobuf/message.h>
#if !defined(MBEDTLS_SSL_PROTO_DTLS)
#error "DTLS not supported by this build of MBEDTLS ?"
#endif
#include "thread_slinger.h"
#include "posix_fe.h"
#include "dll3.h"
#include <map>
#include <deque>
namespace ProtoSSL {
namespace DTLS {
class DTLS_PacketHeader_m; // forward
};
};
namespace ProtoSSL {
typedef google::protobuf::Message MESSAGE;
class ProtoSSLMsgs;
/*************************** ProtoSSLCertParams ***************************/
struct ProtoSSLCertParams
{
const std::string caCert;
const std::string myCert;
const std::string myKey;
const std::string myKeyPassword;
ProtoSSLCertParams(const std::string &_caCert, // file:/...
const std::string &_myCert, // file:/...
const std::string &_myKey, // file:/...
const std::string &_myKeyPassword);
~ProtoSSLCertParams(void);
};
/*************************** ProtoSSLConnClient ***************************/
class ProtoSSLConnClient;
typedef DLL3::List<ProtoSSLConnClient, 1/*uniqueID*/,
true/*lockWarn*/,true/*validate*/> ClientList_t;
struct ProtoSSLPeerInfo
{
std::string ipaddr;
std::string common_name;
std::string pkcs9_email;
std::string org_unit;
};
class ProtoSSLConnClient : public ClientList_t::Links
{
friend class ProtoSSLMsgs;
friend class ProtoSSLConnServer;
bool _ok;
bool send_close_notify;
bool ssl_initialized;
bool net_initialized;
mbedtls_net_context netctx;
mbedtls_ssl_context sslctx;
mbedtls_timing_delay_context timer;
std::string rcvbuf;
std::string outbuf;
ProtoSSLMsgs * msgs;
bool use_tcp;
// private so only ProtoSSLMsgs can make it.
ProtoSSLConnClient(ProtoSSLMsgs * _msgs, mbedtls_net_context new_netctx,
bool _use_tcp,
unsigned char *client_ip, size_t cliip_len);
ProtoSSLConnClient(ProtoSSLMsgs * _msgs,
const std::string &remoteHost, int remotePort,
bool _use_tcp);
bool init_common(unsigned char *client_ip, size_t cliip_len); // returns ok
WaitUtil::Lockable ssl_lock;
public:
static const uint32_t MAX_MSG_SIZE = MBEDTLS_SSL_MAX_CONTENT_LEN;
virtual ~ProtoSSLConnClient(void);
int get_fd(void) const { return netctx.fd; };
enum read_return_t {
GOT_DISCONNECT,
READ_MORE,
GOT_TIMEOUT,
GOT_MESSAGE
};
// if you're using dtlsQ, do not use these two.
read_return_t handle_read(MESSAGE &msg);
bool send_message(const MESSAGE &msg);
// these two are used by dtlsQ.
read_return_t handle_read_raw(std::string &buffer);
bool send_raw(const std::string &buffer);
bool ok(void) const { return _ok; }
bool get_peer_info(ProtoSSLPeerInfo &info);
};
/*************************** ProtoSSLConnServer ***************************/
class ProtoSSLConnServer;
typedef DLL3::List<ProtoSSLConnServer,/*uniqueID*/3,
true/*lockWarn*/,true/*validate*/> ServerList_t;
class ProtoSSLConnServer : public ServerList_t::Links
{
friend class ProtoSSLMsgs;
bool _ok;
mbedtls_net_context netctx;
ProtoSSLMsgs * msgs;
bool use_tcp;
// private so only ProtoSSLMsgs can make it.
ProtoSSLConnServer(ProtoSSLMsgs * _msgs, int listeningPort, bool _use_tcp);
public:
ProtoSSLConnServer() = delete;
virtual ~ProtoSSLConnServer(void);
int get_fd(void) const { return netctx.fd; };
// returns NULL if accept failed for some reason
ProtoSSLConnClient * handle_accept(void);
bool ok(void) const { return _ok; }
};
/*************************** ProtoSSLMsgs ***************************/
class ProtoSSLMsgs
{
friend class ProtoSSLConnServer;
friend class ProtoSSLConnClient;
mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_x509_crt cacert, mycert;
mbedtls_pk_context mykey;
mbedtls_ssl_config sslcfg;
mbedtls_ssl_cookie_ctx cookie_ctx;
bool nonBlockingMode;
bool debugFlag;
bool use_tcp;
ClientList_t clientList;
ServerList_t serverList;
void registerServer(ProtoSSLConnServer * svr);
void unregisterServer(ProtoSSLConnServer * svr);
void registerClient(ProtoSSLConnClient * clnt);
void unregisterClient(ProtoSSLConnClient * clnt);
public:
// read_timeout is in milliseconds
ProtoSSLMsgs(bool _nonBlockingMode, bool _debugFlag = false,
uint32_t read_timeout = 0, bool use_tcp = true,
uint32_t dtls_timeout_min = 1000,
uint32_t dtls_timeout_max = 2000 );
~ProtoSSLMsgs(void);
// returns true if it could load, false if error
bool loadCertificates(const ProtoSSLCertParams ¶ms);
// optional: check if the loaded certs actually validate
bool validateCertificates(void);
ProtoSSLConnServer * startServer(int listeningPort);
ProtoSSLConnClient * startClient(const std::string &remoteHost,
int remotePort);
};
struct ProtoSslDtlsQueueConfig
{
ProtoSslDtlsQueueConfig(void)
{
// fill out defaults!
fragment_size = default_fragment_size;
window_size = default_window_size;
ticks_per_second = default_ticks_per_second;
hearbeat_interval = default_hearbeat_interval;
max_missed_heartbeats = default_max_missed_heartbeats;
max_outstanding_acks = default_max_outstanding_acks;
max_outstanding_nacks = default_max_outstanding_nacks;
num_queues = 0;
}
static const uint32_t default_fragment_size = 1250; // 10^4 bits
static const uint32_t default_window_size = 1000;
static const uint32_t default_ticks_per_second = 25;
static const uint32_t default_hearbeat_interval = 25; // 1 second
static const uint32_t default_max_missed_heartbeats = 3; // 3 seconds
static const uint32_t default_max_outstanding_acks = 1;
static const uint32_t default_max_outstanding_nacks = 1;
static const uint32_t max_queues = 8;
// technically, fragment_size is the size of the data portion of the
// fragment messages NOT counting SSL overhead NOR counting
// DTLS_PacketHeader_m overhead, so........ buyer beware.
uint32_t fragment_size;
uint32_t window_size;
uint32_t ticks_per_second;
uint32_t hearbeat_interval;
// handle_read will return LINK_DOWN when
// this many heartbeats are missed.
uint32_t max_missed_heartbeats;
// advantage to ack/nack packing: can ack several packets in a single
// response. disadvantages: when a single fragment containing several acks
// is lost, all of those frags get retransmitted, even the ones that got
// through; and the acks aren't sent immediately. (if the max is set to 1,
// the heartbeat message with piggybacked acks is forced immediately.)
uint32_t max_outstanding_acks;
uint32_t max_outstanding_nacks;
enum Queue_Type_t { STACK, FIFO };
enum Limit_Type_t { NONE, MESSAGES, BYTES };
struct queue_config_t {
bool reliable;
Queue_Type_t qt;
Limit_Type_t lt;
uint32_t limit;
};
private:
// NOTE indexes returned by add_queue do NOT index
// this array! that's why this is private, to
// point the gun away from the user's foot.
friend class ProtoSslDtlsQueue;
queue_config_t queue_config[max_queues];
uint32_t num_queues;
public:
// this returns the queue_number, which will be 1-N
bool add_queue(uint32_t &queue_number, bool reliable,
Queue_Type_t qt, Limit_Type_t lt, uint32_t limit)
{
if (num_queues >= max_queues)
return false;
queue_config[num_queues].reliable = reliable;
queue_config[num_queues].qt = qt;
queue_config[num_queues].lt = lt;
queue_config[num_queues].limit = limit;
queue_number = ++num_queues; // yes, this is correct.
return true;
}
const queue_config_t &get_queue_config(uint32_t queue_number) const
{
// note queue_numbers are numbered 1-N
if (queue_number > num_queues)
// handle error?
return queue_config[0];
return queue_config[queue_number-1];
}
};
struct ProtoSslDtlsQueueStatistics
{
uint64_t bytes_sent;
uint64_t bytes_received;
uint64_t frags_sent;
uint64_t frags_received;
uint64_t frags_resent;
uint64_t missing_frags_detected;
ProtoSslDtlsQueueStatistics(void) { init(); }
void init(void)
{
bytes_sent = 0;
bytes_received = 0;
frags_sent = 0;
frags_received = 0;
frags_resent = 0;
missing_frags_detected = 0;
}
std::string Format(void);
};
class ProtoSslDtlsQueue
{
const ProtoSslDtlsQueueConfig config;
ProtoSSLConnClient * client;
WaitUtil::Lockable dtls_lock;
bool link_up;
bool link_changed;
bool _ok;
ProtoSslDtlsQueueStatistics stats;
public:
enum read_return_t {
GOT_DISCONNECT,
READ_MORE,
GOT_TIMEOUT,
GOT_MESSAGE,
LINK_DOWN,
LINK_UP
};
enum send_return_t {
SEND_SUCCESS, // message is queued / on the way.
MESSAGE_TOO_BIG, // too big for window_size * fragment_size,
// or just fragment_size on unreliable queue.
BOGUS_QUEUE_NUMBER, // queue number is bogusly bogus.
MSG_NOT_INITIALIZED, // msg.IsInitialized() returned false.
QOS_DROP, // configured queue has exceeded set limits; note this
// is returned for FIFO queues, but not STACK queues,
// because stacks drop from the other end.
CONN_SHUTDOWN // you have called shutdown(), don't call send_message
};
private:
struct dtls_send_event : public ThreadSlinger::thread_slinger_message
{
enum { TICK, MSG, ACK, NACK, DIE } type;
bool reliable; // used only for MSG
uint32_t seqno; // used by ACK/NACK; NOT valid for MSG
std::string encoded_msg; // used by MSG
};
struct dtls_read_event : public ThreadSlinger::thread_slinger_message
{
read_return_t retcode;
std::string encoded_msg;
};
static const int pool_size = 1000;
static const int other_pool_size = 100;
// only type==MSG from msg_pool, rest from other_pool.
// this prevents deadlocks when msg_pool is extinguished;
// acks can still get through from recv_thread.
ThreadSlinger::thread_slinger_pool<dtls_send_event> send_msg_pool;
ThreadSlinger::thread_slinger_pool<dtls_send_event> send_other_pool;
ThreadSlinger::thread_slinger_pool<dtls_read_event> read_pool;
void send_event_release(dtls_send_event *dte) {
if (dte) {
if (dte->type == dtls_send_event::MSG)
send_msg_pool.release(dte);
else
send_other_pool.release(dte);
}
}
typedef ThreadSlinger::thread_slinger_queue<dtls_send_event> dtls_thread_queue_t;
typedef ThreadSlinger::thread_slinger_queue<dtls_read_event> dtls_read_queue_t;
dtls_thread_queue_t send_q;
dtls_read_queue_t recv_q;
// this is always config.num_queues + 1, because
// queues[0] is always send_q. also note that
// Config::add_queue always returns 1-N so we can just
// use queues[queue_number].
uint32_t num_queues;
dtls_thread_queue_t * queues[ProtoSslDtlsQueueConfig::max_queues];
uint32_t queue_sizes[ProtoSslDtlsQueueConfig::max_queues]; // bytes
// thread maintenance junk
// 0 = tick_thread, 1 = recv_thread, 2 = send_thread.
static const uint32_t num_threads = 3;
pthread_t thread_ids[num_threads];
bool thread_started[num_threads];
uint32_t startWhich;
WaitUtil::Waitable startThreadSync;
bool start_thread(uint32_t which, pthread_t *);
static void *_start_thread(void *);
pxfe_pipe closer_pipe;
// tick thread
void tick_thread(void);
uint32_t tick; // for debug, don't depend on it, due to wrappage.
// send thread
void send_thread(void);
void handle_tick(void);
// note queue_number=-1 means we're trying again on an ondeck
// message, so we don't have to account for it again in queue_sizes.
// false ret means send window is full, couldn't send.
bool handle_send_msg(dtls_send_event *dte, int queue_number = -1);
void handle_nack(dtls_send_event *dte);
void send_heartbeat(void) { WaitUtil::Lock l(&dtls_lock); send_frag(NULL); }
struct dtls_fragment : public ThreadSlinger::thread_slinger_message
{
dtls_fragment(void);
~dtls_fragment(void);
void init();
int refcount;
uint32_t seqno; // non-modulo'd original seqno.
bool delivered; // used to detect lost ack and prevent double-delivery
uint32_t age; // set to 0 on entry to send_window.
std::string fragment; // body, not header
ProtoSSL :: DTLS :: DTLS_PacketHeader_m *pkthdr;
// debug
std::string print(void) const;
};
struct fragpool_t {
private:
ThreadSlinger::thread_slinger_pool<dtls_fragment> fragpool;
public:
// alloc from fragpool first; if empty, new.
inline dtls_fragment *alloc(void); // note frag->refcount == 1
inline void deref(dtls_fragment *);
} fragpool;
// fragsender. if we have an ack or nack to send, but
// don't want to send them immediately, we can wait until
// we have something else to send-- put them here, on deck.
std::deque<uint32_t> ondeck_ack_seq_nos;
std::deque<uint32_t> ondeck_nack_seq_nos;
void push_ondeck_acks(uint32_t seqno);
std::string frag_send_buffer; // reuse, to prevent excessive reallocs
// invoke with NULL to just send heartbeat, acknacks.
void send_frag(dtls_fragment *, const char *reason = NULL);
// this is the next sequence number we're going to send.
// the position in send_window where it belongs is
// "send_seqno % config.window_size"
uint32_t send_seqno;
std::vector<dtls_fragment*> send_window;
// for calculating retransmit age.
uint64_t rtd_rsp_timestamp;
time_t last_rtd_req_time;
uint32_t retransmit_age; // in ticks
// recv thread
void recv_thread(void);
void handle_got_frag(void);
// returns number of frags consumed from recv_reassembly;
uint32_t recv_reassemble_deliver(uint32_t seqno);
void handle_recv_ack(uint32_t recv_seq_no);
void handle_recv_nack(uint32_t recv_seq_no);
// next seqno to be received, assembled, and delivered
// to application.
uint32_t recv_seqno;
std::string frag_recv_buffer; // reuse, to prevent excessive reallocs
std::vector<dtls_fragment *> recv_frag_list; // reuse to prevent reallocs
// see the big comment in got_frag to see how these are used.
std::vector<dtls_fragment*> recv_window;
typedef std::map<uint32_t/*seqno*/,dtls_fragment*> ReassemblyMap;
ReassemblyMap recv_reassembly;
uint32_t ticks_without_recv; // trigger for LINK_DOWN
uint32_t ticks_without_send; // trigger for hearbeat
public:
// provide a connected SSLConnClient object, and this object
// takes over ownership of it. when this class is deleted,
// the SSL client will be deleted (connection closed) too.
ProtoSslDtlsQueue (const ProtoSslDtlsQueueConfig &_config,
ProtoSSLConnClient *);
// call this after construction to see if construction was okay.
bool ok(void) const { return _ok; }
// if you didn't call shutdown, this will do it for you. it will
// also delete the SSLConnClient for you.
~ProtoSslDtlsQueue(void);
void get_stats(ProtoSslDtlsQueueStatistics *stats);
send_return_t send_message(uint32_t queue_number, const MESSAGE &);
// don't use the ConnClient's get_fd to select. just call this and
// it blocks until something happens. if you delete this object
// from another thread, you'll get a DISCONNECT from this call.
// sorry i know this means you can't do multiple descriptors or
// multiple DtlsQ's in one thread, but there's reasons why this is.
// if we're truly desperate for that in the future, we could
// expose the recv_q to the caller so the caller could do a
// multi_dequeue on all of them.
read_return_t handle_read(MESSAGE &msg);
// shut down the dtlsq connection. if you've got a thread blocked
// in handle_read, it will wake up immediately with GOT_DISCONNECT.
// it will also close the SSLConnClient. at this point the DtlsQ
// is dead and there is nothing left for it but to be deleted.
// NOTE you don't have to call shutdown, as the destructor will
// do the shutdown; but having a separate shutdown method is useful
// if you want to control when the object gets deleted, or your
// thread calling handle_read can't be guaranteed to not access
// the pointer after deletion.
void shutdown(void);
};
}; // namespace ProtoSSL
#endif /* __LIBPROTOSSL2_H__ */
|
Sun-CX/reactor
|
netc/tests/Buffer-Test.cpp
|
<reponame>Sun-CX/reactor<gh_stars>1-10
//
// Created by suncx on 2020/8/19.
//
#include "Buffer.h"
#include "ConsoleStream.h"
using reactor::net::Buffer;
static void test_find() {
Buffer buf;
char msg[] = "hello\r\nworld\r\n.";
buf.append(msg, sizeof(msg));
auto idx = buf.find_crlf();
RC_DEBUG << "first crlf index: " << idx - buf.begin() - buf.reserved_bytes();
idx = buf.find_crlf(idx + 2);
RC_DEBUG << "second crlf index: " << idx - buf.begin() - buf.reserved_bytes();
}
void test() {
Buffer buffer(8);
buffer.append("hello");
// cout << buffer.retrieve_all_string() << endl;
buffer.append("world");
// cout << buffer.retrieve_all_string() << endl;
buffer.retrieve(8);
buffer.append("fuck");
RC_DEBUG << buffer.retrieve_all_string();
}
int main(int argc, const char *argv[]) {
// test_find();
test();
return 0;
}
|
andrew-t-james/personal-project
|
src/Reducers/__test__/auth.test.js
|
<filename>src/Reducers/__test__/auth.test.js
import { authReducer } from '../auth';
import * as actions from '../../Actions/auth';
describe('', () => {
const id = 1;
const name = 'Steve';
const image = 'some-url';
const mockUser = {
uid: id,
displayName: name,
photoURL: image
};
test('should return a newUser when case is GOOGLE_LOGIN ', () => {
const { googleSignInAction } = actions;
const expected = {
id,
name,
image
};
const result = authReducer(null, googleSignInAction(mockUser));
expect(result).toEqual(expected);
});
test('should return a newUser when case is GITHUB_LOGIN ', () => {
const { githubLoginAction } = actions;
const expected = {
id,
name,
image
};
const result = authReducer(null, githubLoginAction(mockUser));
expect(result).toEqual(expected);
});
test('should return a newUser when case is TWITTER_LOGIN ', () => {
const { twitterLoginAction } = actions;
const expected = {
id,
name,
image
};
const result = authReducer(null, twitterLoginAction(mockUser));
expect(result).toEqual(expected);
});
test('should return a newUser when case is FACEBOOK_LOGIN ', () => {
const { facebookLoginAction } = actions;
const expected = {
id,
name,
image
};
const result = authReducer(null, facebookLoginAction(mockUser));
expect(result).toEqual(expected);
});
test('should return a newUser when case is GOOGLE_LOGOUT ', () => {
const { googleSignOutAction } = actions;
const expected = {};
const result = authReducer(null, googleSignOutAction(mockUser));
expect(result).toEqual(expected);
});
test('should return default state', () => {
const expected = {};
const result = authReducer(undefined, jest.fn());
expect(result).toEqual(expected);
});
});
|
satryarangga/triparoom
|
src/containers/flight/confirmation.js
|
<reponame>satryarangga/triparoom
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Header from '../../components/layout/header';
import Footer from '../../components/layout/footer';
import Breadcrumb from '../../utils/breadcrumb';
import OrderLeft from '../../components/flight/confirmation/left';
import Payment from '../../components/flight/confirmation/payment';
import { fetchFlightOrder } from '../../actions/actionOrderFlight';
import NoData from '../../utils/nodata';
class FlightConfirmation extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.props.fetchFlightOrder();
}
renderData() {
if(this.props.orderFlight.order.total == undefined) {
return <div className="cp-pinwheel"></div>
}
if(this.props.orderFlight.order.order_id == null) {
return (
<NoData label="Belum ada pemesanan. Silahkan melakukan pemesanan pesawat terlebih dahulu" type="penerbangan" />
);
}
return(
<div>
<div className="col-md-12">
<Breadcrumb label="Konfirmasi Penerbangan" />
</div>
<div className="col-md-3">
<OrderLeft order={this.props.orderFlight.order} />
</div>
<div className="col-md-9">
<div>
<Payment order={this.props.orderFlight.order} contact={this.props.match.params} />
</div>
</div>
</div>
);
}
render() {
return(
<div>
<Header />
<div className="inner-body">
<div className="container">
<div className="row">
{this.renderData()}
</div>
</div>
</div>
<Footer />
</div>
);
}
}
function mapStateToProps(state) {
return {
orderFlight: state.orderFlight
}
}
export default connect(mapStateToProps, { fetchFlightOrder }) (FlightConfirmation);
|
ScalablyTyped/SlinkyTyped
|
d/dojo/src/main/scala/typingsSlinky/dojo/dojo/main/i18n.scala
|
<gh_stars>10-100
package typingsSlinky.dojo.dojo.main
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation._
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojo/main.i18n.html
*
* This module implements the dojo/i18n! plugin and the v1.6- i18n API
* We choose to include our own plugin to leverage functionality already contained in dojo
* and thereby reduce the size of the plugin compared to various loader implementations. Also, this
* allows foreign AMD loaders to be used without their plugins.
*
*/
@js.native
trait i18n extends js.Object {
/**
*
*/
var cache: js.Object = js.native
/**
*
*/
var dynamic: Boolean = js.native
/**
*
*/
var unitTests: js.Array[_] = js.native
/**
*
* @param moduleName
* @param bundleName
* @param locale
*/
def getL10nName(moduleName: js.Any, bundleName: js.Any, locale: js.Any): String = js.native
/**
*
* @param moduleName
* @param bundleName
* @param locale
*/
def getLocalization(moduleName: js.Any, bundleName: js.Any, locale: js.Any): js.Any = js.native
/**
* id is in one of the following formats
*
* /nls/
* => load the bundle, localized to config.locale; load all bundles localized to
* config.extraLocale (if any); return the loaded bundle localized to config.locale.
* /nls//
* => load then return the bundle localized to
* preload/nls//
* => for config.locale and all config.extraLocale, load all bundles found
* in the best-matching bundle rollup. A value of 1 is returned, which
* is meaningless other than to say the plugin is executing the requested
* preloads
*
* In cases 1 and 2, is always normalized to an absolute module id upon entry; see
* normalize. In case 3, it is assumed to be absolute; this is arranged by the builder.
*
* To load a bundle means to insert the bundle into the plugin's cache and publish the bundle
* value to the loader. Given , , and a particular , the cache key
*
* <path>/nls/<bundle>/<locale>
* will hold the value. Similarly, then plugin will publish this value to the loader by
*
* define("<path>/nls/<bundle>/<locale>", <bundle-value>);
* Given this algorithm, other machinery can provide fast load paths be preplacing
* values in the plugin's cache, which is public. When a load is demanded the
* cache is inspected before starting any loading. Explicitly placing values in the plugin
* cache is an advanced/experimental feature that should not be needed; use at your own risk.
*
* For the normal AMD algorithm, the root bundle is loaded first, which instructs the
* plugin what additional localized bundles are required for a particular locale. These
* additional locales are loaded and a mix of the root and each progressively-specific
* locale is returned. For example:
*
* The client demands "dojo/i18n!some/path/nls/someBundle
* The loader demands load(some/path/nls/someBundle)
* This plugin require's "some/path/nls/someBundle", which is the root bundle.
* Assuming config.locale is "ab-cd-ef" and the root bundle indicates that localizations
* are available for "ab" and "ab-cd-ef" (note the missing "ab-cd", then the plugin
* requires "some/path/nls/ab/someBundle" and "some/path/nls/ab-cd-ef/someBundle"
* Upon receiving all required bundles, the plugin constructs the value of the bundle
* ab-cd-ef as...
* mixin(mixin(mixin({}, require("some/path/nls/someBundle"),
* require("some/path/nls/ab/someBundle")),
* require("some/path/nls/ab-cd-ef/someBundle"));
*
* This value is inserted into the cache and published to the loader at the
* key/module-id some/path/nls/someBundle/ab-cd-ef.
*
* The special preload signature (case 3) instructs the plugin to stop servicing all normal requests
* (further preload requests will be serviced) until all ongoing preloading has completed.
*
* The preload signature instructs the plugin that a special rollup module is available that contains
* one or more flattened, localized bundles. The JSON array of available locales indicates which locales
* are available. Here is an example:
*
* *preload*some/path/nls/someModule*["root", "ab", "ab-cd-ef"]
* This indicates the following rollup modules are available:
*
* some/path/nls/someModule_ROOT
* some/path/nls/someModule_ab
* some/path/nls/someModule_ab-cd-ef
* Each of these modules is a normal AMD module that contains one or more flattened bundles in a hash.
* For example, assume someModule contained the bundles some/bundle/path/someBundle and
* some/bundle/path/someOtherBundle, then some/path/nls/someModule_ab would be expressed as follows:
*
* define({
* some/bundle/path/someBundle:<value of someBundle, flattened with respect to locale ab>,
* some/bundle/path/someOtherBundle:<value of someOtherBundle, flattened with respect to locale ab>,
* });
* E.g., given this design, preloading for locale=="ab" can execute the following algorithm:
*
* require(["some/path/nls/someModule_ab"], function(rollup){
* for(var p in rollup){
* var id = p + "/ab",
* cache[id] = rollup[p];
* define(id, rollup[p]);
* }
* });
* Similarly, if "ab-cd" is requested, the algorithm can determine that "ab" is the best available and
* load accordingly.
*
* The builder will write such rollups for every layer if a non-empty localeList profile property is
* provided. Further, the builder will include the following cache entry in the cache associated with
* any layer.
*
* "*now":function(r){r(['dojo/i18n!*preload*<path>/nls/<module>*<JSON array of available locales>']);}
* The *now special cache module instructs the loader to apply the provided function to context-require
* with respect to the particular layer being defined. This causes the plugin to hold all normal service
* requests until all preloading is complete.
*
* Notice that this algorithm is rarely better than the standard AMD load algorithm. Consider the normal case
* where the target locale has a single segment and a layer depends on a single bundle:
*
* Without Preloads:
*
* Layer loads root bundle.
* bundle is demanded; plugin loads single localized bundle.
* With Preloads:
*
* Layer causes preloading of target bundle.
* bundle is demanded; service is delayed until preloading complete; bundle is returned.
* In each case a single transaction is required to load the target bundle. In cases where multiple bundles
* are required and/or the locale has multiple segments, preloads still requires a single transaction whereas
* the normal path requires an additional transaction for each additional bundle/locale-segment. However all
* of these additional transactions can be done concurrently. Owing to this analysis, the entire preloading
* algorithm can be discard during a build by setting the has feature dojo-preload-i18n-Api to false.
*
* @param id
* @param require
* @param load
*/
def load(id: js.Any, require: js.Any, load: js.Any): Unit = js.native
/**
* id may be relative.
* preload has form *preload*<path>/nls/<module>*<flattened locales> and
* therefore never looks like a relative
*
* @param id
* @param toAbsMid
*/
def normalize(id: js.Any, toAbsMid: js.Any): js.Any = js.native
/**
*
* @param locale
*/
def normalizeLocale(locale: js.Any): js.Any = js.native
}
object i18n {
@scala.inline
def apply(
cache: js.Object,
dynamic: Boolean,
getL10nName: (js.Any, js.Any, js.Any) => String,
getLocalization: (js.Any, js.Any, js.Any) => js.Any,
load: (js.Any, js.Any, js.Any) => Unit,
normalize: (js.Any, js.Any) => js.Any,
normalizeLocale: js.Any => js.Any,
unitTests: js.Array[_]
): i18n = {
val __obj = js.Dynamic.literal(cache = cache.asInstanceOf[js.Any], dynamic = dynamic.asInstanceOf[js.Any], getL10nName = js.Any.fromFunction3(getL10nName), getLocalization = js.Any.fromFunction3(getLocalization), load = js.Any.fromFunction3(load), normalize = js.Any.fromFunction2(normalize), normalizeLocale = js.Any.fromFunction1(normalizeLocale), unitTests = unitTests.asInstanceOf[js.Any])
__obj.asInstanceOf[i18n]
}
@scala.inline
implicit class i18nOps[Self <: i18n] (val x: Self) extends AnyVal {
@scala.inline
def duplicate: Self = (js.Dynamic.global.Object.assign(js.Dynamic.literal(), x)).asInstanceOf[Self]
@scala.inline
def combineWith[Other <: js.Any](other: Other): Self with Other = (js.Dynamic.global.Object.assign(js.Dynamic.literal(), x, other.asInstanceOf[js.Any])).asInstanceOf[Self with Other]
@scala.inline
def withCache(value: js.Object): Self = {
val ret = this.duplicate
ret.asInstanceOf[js.Dynamic].updateDynamic("cache")(value.asInstanceOf[js.Any])
ret
}
@scala.inline
def withDynamic(value: Boolean): Self = {
val ret = this.duplicate
ret.asInstanceOf[js.Dynamic].updateDynamic("dynamic")(value.asInstanceOf[js.Any])
ret
}
@scala.inline
def withGetL10nName(value: (js.Any, js.Any, js.Any) => String): Self = {
val ret = this.duplicate
ret.asInstanceOf[js.Dynamic].updateDynamic("getL10nName")(js.Any.fromFunction3(value))
ret
}
@scala.inline
def withGetLocalization(value: (js.Any, js.Any, js.Any) => js.Any): Self = {
val ret = this.duplicate
ret.asInstanceOf[js.Dynamic].updateDynamic("getLocalization")(js.Any.fromFunction3(value))
ret
}
@scala.inline
def withLoad(value: (js.Any, js.Any, js.Any) => Unit): Self = {
val ret = this.duplicate
ret.asInstanceOf[js.Dynamic].updateDynamic("load")(js.Any.fromFunction3(value))
ret
}
@scala.inline
def withNormalize(value: (js.Any, js.Any) => js.Any): Self = {
val ret = this.duplicate
ret.asInstanceOf[js.Dynamic].updateDynamic("normalize")(js.Any.fromFunction2(value))
ret
}
@scala.inline
def withNormalizeLocale(value: js.Any => js.Any): Self = {
val ret = this.duplicate
ret.asInstanceOf[js.Dynamic].updateDynamic("normalizeLocale")(js.Any.fromFunction1(value))
ret
}
@scala.inline
def withUnitTests(value: js.Array[_]): Self = {
val ret = this.duplicate
ret.asInstanceOf[js.Dynamic].updateDynamic("unitTests")(value.asInstanceOf[js.Any])
ret
}
}
}
|
JenoDK/wk-app
|
src/main/java/com/jeno/fantasyleague/ui/common/tabsheet/CustomMenuBar.java
|
<filename>src/main/java/com/jeno/fantasyleague/ui/common/tabsheet/CustomMenuBar.java
package com.jeno.fantasyleague.ui.common.tabsheet;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import com.google.common.collect.Maps;
import com.vaadin.flow.component.ClickEvent;
import com.vaadin.flow.component.ComponentEventListener;
import com.vaadin.flow.component.contextmenu.MenuItem;
import com.vaadin.flow.component.contextmenu.SubMenu;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.menubar.MenuBar;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
public class CustomMenuBar extends MenuBar {
private VerticalLayout tabLayout;
private String currentId;
Map<String, ComponentCreationFunction> functions;
Map<String, LazyTabComponent> initializedTabs;
public CustomMenuBar(VerticalLayout tabLayout) {
this.tabLayout = tabLayout;
this.functions = Maps.newHashMap();
this.initializedTabs = Maps.newHashMap();
setWidth("100%");
}
public MenuItem addItem(VaadinIcon icon, String text, ComponentEventListener<ClickEvent<MenuItem>> listener) {
HorizontalLayout layout = new HorizontalLayout();
layout.add(icon.create(), new Label(text));
return addItem(layout, listener);
}
public CustomMenuItem addLazyItem(Optional<SubMenu> subMenu, String id, String caption, ComponentCreationFunction function, ComponentEventListener<ClickEvent<MenuItem>> clickListener) {
if (id == null || id.isEmpty()) {
throw new RuntimeException("LazyTabs does not work with tabs without an ID");
}
functions.put(id, function);
ComponentEventListener<ClickEvent<MenuItem>> listener = event -> {
if (!Objects.equals(id, currentId)) {
clickListener.onComponentEvent(event);
if (initializedTabs.containsKey(id)) {
initializedTabs.values().forEach(LazyTabComponent::hide);
initializedTabs.get(id).show();
} else if (functions.containsKey(id)) {
initializedTabs.values().forEach(LazyTabComponent::hide);
LazyTabComponent tabComponent = functions.get(id).createComponent();
tabLayout.add(tabComponent);
initializedTabs.put(id, tabComponent);
}
currentId = id;
}
};
MenuItem menuItem;
if (subMenu.isPresent()) {
menuItem = subMenu.get().addItem(caption, listener);
} else {
menuItem = addItem(caption, listener);
}
return new CustomMenuItem(menuItem, listener);
}
public interface ComponentCreationFunction {
LazyTabComponent createComponent();
}
public class CustomMenuItem {
private MenuItem item;
private ComponentEventListener<ClickEvent<MenuItem>> listener;
public CustomMenuItem(MenuItem item, ComponentEventListener<ClickEvent<MenuItem>> listener) {
this.item = item;
this.listener = listener;
}
public MenuItem getItem() {
return item;
}
public ComponentEventListener<ClickEvent<MenuItem>> getListener() {
return listener;
}
}
}
|
rackeric/rack
|
commands/filescommands/objectcommands/deletemetadata.go
|
<filename>commands/filescommands/objectcommands/deletemetadata.go
package objectcommands
import (
"fmt"
"strings"
"github.com/rackspace/rack/commandoptions"
"github.com/rackspace/rack/handler"
"github.com/rackspace/rack/internal/github.com/codegangsta/cli"
osObjects "github.com/rackspace/rack/internal/github.com/rackspace/gophercloud/openstack/objectstorage/v1/objects"
"github.com/rackspace/rack/internal/github.com/rackspace/gophercloud/rackspace/objectstorage/v1/objects"
"github.com/rackspace/rack/util"
)
var deleteMetadata = cli.Command{
Name: "delete-metadata",
Usage: util.Usage(commandPrefix, "delete-metadata", "--name <objectName> --container <containerName> --metadata-keys <metadataKeys>"),
Description: "Delete specific metadata from the given object.",
Action: actionDeleteMetadata,
Flags: commandoptions.CommandFlags(flagsDeleteMetadata, keysDeleteMetadata),
BashComplete: func(c *cli.Context) {
commandoptions.CompleteFlags(commandoptions.CommandFlags(flagsDeleteMetadata, keysDeleteMetadata))
},
}
func flagsDeleteMetadata() []cli.Flag {
return []cli.Flag{
cli.StringFlag{
Name: "name",
Usage: "[required] The object name from which to delete the metadata.",
},
cli.StringFlag{
Name: "container",
Usage: "[required] The name of the container that holds the object.",
},
cli.StringFlag{
Name: "metadata-keys",
Usage: "[required] A comma-separated string of metadata keys to delete from the container.",
},
}
}
var keysDeleteMetadata = []string{}
type paramsDeleteMetadata struct {
objectName string
containerName string
metadataKeys []string
}
type commandDeleteMetadata handler.Command
func actionDeleteMetadata(c *cli.Context) {
command := &commandDeleteMetadata{
Ctx: &handler.Context{
CLIContext: c,
},
}
handler.Handle(command)
}
func (command *commandDeleteMetadata) Context() *handler.Context {
return command.Ctx
}
func (command *commandDeleteMetadata) Keys() []string {
return keysDeleteMetadata
}
func (command *commandDeleteMetadata) ServiceClientType() string {
return serviceClientType
}
func (command *commandDeleteMetadata) HandleFlags(resource *handler.Resource) error {
err := command.Ctx.CheckFlagsSet([]string{"name", "container", "metadata-keys"})
if err != nil {
return err
}
c := command.Ctx.CLIContext
containerName := c.String("container")
if err := CheckContainerExists(command.Ctx.ServiceClient, containerName); err != nil {
return err
}
metadataKeys := strings.Split(c.String("metadata-keys"), ",")
for i, k := range metadataKeys {
metadataKeys[i] = strings.Title(k)
}
resource.Params = ¶msDeleteMetadata{
objectName: c.String("name"),
containerName: containerName,
metadataKeys: metadataKeys,
}
return nil
}
func (command *commandDeleteMetadata) Execute(resource *handler.Resource) {
params := resource.Params.(*paramsDeleteMetadata)
containerName := params.containerName
objectName := params.objectName
currentMetadata, err := objects.Get(command.Ctx.ServiceClient, containerName, objectName, nil).ExtractMetadata()
if err != nil {
resource.Err = err
return
}
for _, k := range params.metadataKeys {
currentMetadata[k] = ""
}
updateOpts := osObjects.UpdateOpts{
Metadata: currentMetadata,
}
updateResponse := objects.Update(command.Ctx.ServiceClient, containerName, objectName, updateOpts)
if updateResponse.Err != nil {
resource.Err = updateResponse.Err
return
}
resource.Result = fmt.Sprintf("Successfully deleted metadata with keys [%s] from object [%s].\n", strings.Join(params.metadataKeys, ", "), objectName)
}
|
kiran-blockchain/comcast-india-go
|
more-examples/11-if/exercises/03-arg-count/solution/main.go
|
<reponame>kiran-blockchain/comcast-india-go
// Copyright © 2018 <NAME>
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
// For more tutorials : https://learngoprogramming.com
// In-person training : https://www.linkedin.com/in/inancgumus/
// Follow me on twitter: https://twitter.com/inancgumus
package main
import (
"fmt"
"os"
)
func main() {
var (
args = os.Args
l = len(args) - 1
)
if l == 0 {
fmt.Println("Give me args")
} else if l == 1 {
fmt.Printf("There is one: %q\n", args[1])
} else if l == 2 {
fmt.Printf(
`There are two: "%s %s"`+"\n",
args[1], args[2],
)
} else {
fmt.Printf("There are %d arguments\n", l)
}
}
|
mc-chinju/bitflyer-api
|
spec/lib/bitflyer_api/private/private_spec.rb
|
<reponame>mc-chinju/bitflyer-api
require "spec_helper"
RSpec.describe "HTTP Private Api" do
let!(:client){ BitflyerApi.client }
it "Needs API_KEY and API_SECRET" do
VCR.use_cassette("needs_access_key") do
response = client.my_permissions
aggregate_failures do
expect(response["status"]).to eq -500
expect(response["error_message"]).to eq "ACCESS-KEY header is required"
end
end
end
end
|
fesp21/harbor
|
webApp/server/gmail/setHistoryStartId.js
|
import User from '../models/User'
import * as api from './api'
import logger from '../log'
export default async function setHistoryStartId(userId) {
const oauth2Client = api.getAuthClient()
const user = await User.findById(userId, 'googleId googleToken gmailHistoryStartId')
if (user.gmailHistoryStartId) {
return
}
oauth2Client.setCredentials(user.googleToken)
try {
const list = await api.messagesList({
userId: user.googleId,
maxResults: 1,
auth: oauth2Client
})
if (list && list.messages && list.messages[0]) {
const lastMessage = await api.getMessage({
userId: user.googleId,
id: list.messages[0].id,
auth: oauth2Client
})
if (lastMessage && lastMessage.historyId) {
User.updateOne({ _id: userId }, { gmailHistoryStartId: lastMessage.historyId }).exec()
}
}
} catch (error) {
logger.error(error)
}
}
|
open-hand/hzero-front
|
packages/hzero-front-hrpt/src/models/templateManage.js
|
<filename>packages/hzero-front-hrpt/src/models/templateManage.js
/**
* @date 2018-12-06
* @author: CJ <<EMAIL>>
*/
import { isEmpty } from 'lodash';
import { getResponse, createPagination } from 'utils/utils';
import { queryMapIdpValue } from 'hzero-front/lib/services/api';
import {
fetchTemplateManageList,
createTemplateManage,
editTemplateManage,
fetchTemplateHeaderDetail,
fetchTemplateLine,
deleteTemplateManage,
createTemplateLine,
editTemplateLine,
fetchTemplateLineDetail,
deleteTemplateLine,
} from '../services/templateManageService';
export default {
namespace: 'templateManage',
state: {
list: {}, // 列表数据
code: {}, // 值集
pagination: {}, // 分页数据
templateTypeCode: [], // 模板类型
header: {}, // 模板管理头
line: {}, // 模板管理行
lineDetail: {}, // 行详情
linePagination: {}, // 行分页器
fileList: [], // 文件
detailWordEditor: {
// [record.fileUrl]: record, // 存储 word编辑 的记录
},
},
effects: {
// 获取模板管理列表
* fetchTemplateManageList({ payload }, { call, put }) {
const res = yield call(fetchTemplateManageList, payload);
const result = getResponse(res);
if (result) {
yield put({
type: 'updateState',
payload: {
list: result,
pagination: createPagination(result),
},
});
}
},
// 统一获取值级的数据
* batchCode({ payload }, { put, call }) {
const { lovCodes } = payload;
const code = getResponse(yield call(queryMapIdpValue, lovCodes));
if (!isEmpty(code)) {
yield put({
type: 'updateState',
payload: {
code,
},
});
}
},
// 获取模板管理头详情
* fetchTemplateHeaderDetail({ payload }, { call, put }) {
const res = yield call(fetchTemplateHeaderDetail, payload);
const result = getResponse(res);
if (result) {
yield put({
type: 'updateState',
payload: {
header: result,
},
});
}
},
// 获取模板管理行
* fetchTemplateLine({ payload }, { call, put }) {
const res = yield call(fetchTemplateLine, payload);
const result = getResponse(res);
if (result) {
yield put({
type: 'updateState',
payload: {
line: result,
linePagination: createPagination(result),
},
});
}
},
// 获取模板管理行详情
* fetchTemplateLineDetail({ payload }, { call, put }) {
const res = yield call(fetchTemplateLineDetail, payload);
const result = getResponse(res);
if (result) {
yield put({
type: 'updateState',
payload: {
lineDetail: result,
fileList: [
{
uid: '-1',
name: result.templateFileName,
status: 'done',
url: result.templateUrl,
},
],
},
});
}
return result;
},
// 添加模板管理
* createTemplateManage({ payload }, { call }) {
const res = yield call(createTemplateManage, { ...payload });
return getResponse(res);
},
// 编辑模板管理
* editTemplateManage({ payload }, { call }) {
const res = yield call(editTemplateManage, { ...payload });
return getResponse(res);
},
// 删除模板管理
* deleteTemplateManage({ payload }, { call }) {
const res = yield call(deleteTemplateManage, { ...payload });
return getResponse(res);
},
// 新建模板管理行
* createTemplateLine({ payload }, { call }) {
const res = yield call(createTemplateLine, { ...payload });
return getResponse(res);
},
// 编辑模板管理行
* editTemplateLine({ payload }, { call }) {
const res = yield call(editTemplateLine, { ...payload });
return getResponse(res);
},
// 删除模板管理行
* deleteTemplateLine({ payload }, { call }) {
const res = yield call(deleteTemplateLine, { ...payload });
return getResponse(res);
},
},
reducers: {
updateState(state, action) {
return {
...state,
...action.payload,
};
},
},
};
|
LightSun/Android-ImagePick
|
ImagePickApp/app/src/main/java/com/heaven7/android/pick/app/MainActivity.java
|
/*
package com.heaven7.android.pick.app;
import android.Manifest;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.heaven7.android.imagepick0.CameraFragment;
import com.heaven7.core.util.Logger;
import com.heaven7.core.util.PermissionHelper;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity implements CameraFragment.Callback, CameraFragment.IBitmapDelegate {
@BindView(R.id.iv_image)
ImageView mIv_image;
@BindView(R.id.vg_container)
ViewGroup mVg_container;
private CameraFragment mFragment;
private PermissionHelper mHelper = new PermissionHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mIv_image.setVisibility(View.GONE);
mHelper.startRequestPermission(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},
new int[]{1, 2}, new PermissionHelper.ICallback() {
@Override
public void onRequestPermissionResult(String s, int i, boolean b) {
if(b){
// setCameraFragment();
testCropLib();
}
}
});
}
private void testCropLib() {
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
mHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@OnClick(R.id.bt_req_image)
public void onClickRequestBitmap(View view){
mFragment.requestBitmap(this);
}
@OnClick(R.id.iv_image)
public void onClickImage(View view){
mIv_image.setVisibility(View.GONE);
}
@Override
public void onInitFailed(Exception e) {
e.printStackTrace();
}
@Override
public void onInitSuccess() {
Logger.d("MainActivity", "onInitSuccess", "");
}
@Override
public void onBitmap(Bitmap bitmap) {
Logger.d("MainActivity", "onBitmap", "bitmap = " + bitmap);
if(bitmap != null){
mIv_image.setImageBitmap(bitmap);
mIv_image.setVisibility(View.VISIBLE);
}
}
private void setCameraFragment() {
mFragment = new CameraFragment();
mFragment.setCallback(this);
getSupportFragmentManager().beginTransaction()
.replace(R.id.vg_container, mFragment)
.commit();
}
}
*/
|
barak/raidutils
|
raidutil/command.hpp
|
/* Copyright (c) 1996-2004, Adaptec Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the Adaptec Corporation nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef COMMAND_HPP
#define COMMAND_HPP
/****************************************************************************
*
* Created: 7/17/98
*
*****************************************************************************
*
* File Name: Command.hpp
* Module:
* Contributors: <NAME>
* Description: This object provides the common interface to many commands that
* the engine is capable of performing. It is expected that all
* parameters necessary for the completion of the command will be
* gathered by the derived object.
* Version Control:
*
* $Revision$
* $NoKeywords: $
* $Log$
* Revision 1.1.1.1 2004-04-29 10:20:11 bap
* Imported upstream version 0.0.4.
*
*****************************************************************************/
/*** INCLUDES ***/
#include "debug.hpp"
#include "engiface.hpp"
#include "strlist.hpp"
#include "scsiaddr.hpp"
/*** CONSTANTS ***/
/*** TYPES ***/
class Command
{
public:
enum Raid_Type
{
RAID_TYPE_0 = RAID_0,
RAID_TYPE_1 = RAID_1,
RAID_TYPE_3 = RAID_3,
RAID_TYPE_5 = RAID_5,
RAID_TYPE_HOT_SPARE = RAID_HOT_SPARE,
RAID_TYPE_REDIRECT = RAID_REDIRECT
};
// this isn't a mask, this is used to select the mask to use
// so the function can know what address fields to ignore.
enum get_Devs_Mask
{
GET_DEVS_ALL_DEVS,
GET_DEVS_ON_THIS_HBA,
GET_DEVS_ON_THIS_HBA_BUS,
GET_DEVS_ON_THIS_HBA_BUS_ID
};
enum get_Devs_Type
{
GET_SCSI_DASD = DPT_SCSI_DASD,
GET_SCSI_SASD = DPT_SCSI_SASD,
GET_SCSI_PRINTER = DPT_SCSI_PRINTER,
GET_SCSI_PROCESSOR = DPT_SCSI_PROCESSOR,
GET_SCSI_WORM = DPT_SCSI_WORM,
GET_SCSI_CD_ROM = DPT_SCSI_CD_ROM,
GET_SCSI_SCANNER = DPT_SCSI_SCANNER,
GET_SCSI_OPTICAL = DPT_SCSI_OPTICAL,
GET_SCSI_JUKEBOX = DPT_SCSI_JUKEBOX,
GET_SCSI_PRO_ROOT = DPT_SCSI_PRO_ROOT,
GET_SCSI_PRO_CONNECTION = DPT_SCSI_PRO_CONNECTION,
GET_SCSI_HBA = DPT_SCSI_HBA,
GET_SCSI_BCD = DPT_SCSI_BCD,
GET_RAID_BCD = DPT_RAID_BCD,
GET_RAID,
GET_RAID_HOT_SPARE,
GET_RAID_REDIRECT,
GET_ARRAY,
GET_ARRAYNAME
};
enum Dev_Class
{
DEV_CLASS_SOFTWARE_RAID = 0,
DEV_CLASS_HARDWARE_RAID = 1,
DEV_CLASS_PHYSICAL_DEVs = 2,
DEV_CLASS_PHYSICAL_BRIDGES = 3,
DEV_CLASS_ALL_MATCHING = 0xff
};
enum Get_By_Scsi_Address_Mask
{
// see the notes on "MSG_ID_BY_SCSI_ADDR" for the source of these constants.
GET_BY_SCSI_ADDR_IGNORE_LUN_FIELD = 1,
GET_BY_SCSI_ADDR_IGNORE_ID_FIELD = 2,
GET_BY_SCSI_ADDR_IGNORE_BUS_FIELD = 4,
GET_BY_SCSI_ADDR_IGNORE_HBA_FIELD = 8,
GET_BY_SCSI_ADDR_MGR_AND_DEVS_0 = 0, // the doc doesn't say what the difference
GET_BY_SCSI_ADDR_MGR_AND_DEVS_1 = 0x40, // is between these two items
GET_BY_SCSI_ADDR_DEVS = 0x80,
GET_BY_SCSI_ADDR_MGRS = 0xd0
};
class Dpt_Error
{
public:
enum dpt_Error
{
// errors unique to the Command object and its derivitives.
DPT_CMD_ERR_NO_ERROR = 10000,
DPT_CMD_PARSER_ERROR,
DPT_CMD_ERR_INVALID_LIST_TYPE,
DPT_CMD_ERR_CANT_FIND_COMPONENT,
DPT_CMD_ERR_CANT_FIND_HBA_INDEX,
DPT_CMD_ERR_CANT_FIND_HBA_INDEX_NVRAM,
DPT_CMD_ERR_COMPONENT_BUSY,
DPT_CMD_ERR_INVALID_FLASH_IMAGE,
DPT_ERR_VALUE_OUT_OF_RANGE,
DPT_ERR_INVALID_FILE,
DPT_ERR_INVALID_RAID_TYPE,
DPT_ERR_NOT_ENOUGH_MEMORY,
DPT_ERR_TWO_TB_RAID,
DPT_ERR_INVALID_SEGMENT_OFFSET,
DPT_ERR_INVALID_SEGMENT_SIZE,
DPT_ERR_NAME_ALREADY_USED,
// this is not possible (see taskctrl.cpp)
DPT_CMD_ERR_CMD_NOT_POSS_ON_RAID,
DPT_CMD_ERR_CMD_NOT_POSS_ON_HBA,
DPT_CMD_ERR_CMD_NOT_POSS_ON_THIS_DEVICE,
DPT_ERR_POSS_BUFFER_CORRUPTION,
// errors that correspond directly to engine errors
DPT_MSG_RTN_COMPLETED = MSG_RTN_COMPLETED,
DPT_MSG_RTN_STARTED = MSG_RTN_STARTED,
// added to get around 'long enum' compile error
#if (!defined _DPT_SCO)
DPT_MSG_RTN_FAILED = MSG_RTN_FAILED,
#else
#define DPT_MSG_RTN_FAILED MSG_RTN_FAILED
#endif
DPT_MSG_RTN_DATA_OVERFLOW = MSG_RTN_DATA_OVERFLOW,
DPT_MSG_RTN_DATA_UNDERFLOW = MSG_RTN_DATA_UNDERFLOW,
DPT_MSG_RTN_IGNORED = MSG_RTN_IGNORED,
DPT_MSG_RTN_DISCONNECT = MSG_RTN_DISCONNECT,
DPT_ERR_CONN_LIST_ALLOC = ERR_CONN_LIST_ALLOC,
DPT_ERR_SEMAPHORE_ALLOC = ERR_SEMAPHORE_ALLOC,
DPT_ERR_OSD_OPEN_ENGINE = ERR_OSD_OPEN_ENGINE,
DPT_ERR_INVALID_IO_METHOD = ERR_INVALID_IO_METHOD,
DPT_ERR_NO_SMARTROM = ERR_NO_SMARTROM,
DPT_ERR_ENGINE_INIT = ERR_ENGINE_INIT,
DPT_ERR_INVALID_CONN_TAG = ERR_INVALID_CONN_TAG,
DPT_ERR_SEMAPHORE_TIMEOUT = ERR_SEMAPHORE_TIMEOUT,
DPT_ERR_NULL_IO_BUFFER = ERR_NULL_IO_BUFFER,
DPT_ERR_INVALID_TGT_TAG = ERR_INVALID_TGT_TAG,
DPT_ERR_DESTROY_SEMAPHORE = ERR_DESTROY_SEMAPHORE,
DPT_ERR_MEM_ALLOC = ERR_MEM_ALLOC,
DPT_ERR_INVALID_DEV_ADDR = ERR_INVALID_DEV_ADDR,
DPT_ERR_DUPLICATE_NAME = ERR_DUPLICATE_NAME,
DPT_ERR_GET_CCB = ERR_GET_CCB,
DPT_ERR_NO_RAID_DEVICES = ERR_NO_RAID_DEVICES,
DPT_ERR_RESERVE_BLK_SIG = ERR_RESERVE_BLK_SIG,
DPT_ERR_FORMAT_BLK_SIZE = ERR_FORMAT_BLK_SIZE,
DPT_ERR_RAID_REFNUM = ERR_RAID_REFNUM,
DPT_ERR_RAID_COMP_DUPLICATE = ERR_RAID_COMP_DUPLICATE,
DPT_ERR_RAID_COMP_RESTRICT = ERR_RAID_COMP_RESTRICT,
DPT_ERR_RAID_COMP_USED = ERR_RAID_COMP_USED,
DPT_ERR_RAID_COMP_GHOST = ERR_RAID_COMP_GHOST,
DPT_ERR_RAID_COMP_FAILED = ERR_RAID_COMP_FAILED,
DPT_ERR_RAID_TOO_FEW = ERR_RAID_TOO_FEW,
DPT_ERR_RAID_TOO_MANY = ERR_RAID_TOO_MANY,
DPT_ERR_RAID_EVEN = ERR_RAID_EVEN,
DPT_ERR_RAID_ODD = ERR_RAID_ODD,
DPT_ERR_RAID_POWER_2_PLUS = ERR_RAID_POWER_2_PLUS,
DPT_ERR_RAID_CHAN_COUNT = ERR_RAID_CHAN_COUNT,
DPT_ERR_RAID_MIN_STRIPE = ERR_RAID_MIN_STRIPE,
DPT_ERR_RAID_MAX_STRIPE = ERR_RAID_MAX_STRIPE,
DPT_ERR_RAID_ZERO_STRIPES = ERR_RAID_ZERO_STRIPES,
DPT_ERR_RAID_TOO_LARGE = ERR_RAID_TOO_LARGE,
DPT_ERR_RAID_START_CHAN = ERR_RAID_START_CHAN,
DPT_ERR_RAID_SEQ_CHAN = ERR_RAID_SEQ_CHAN,
DPT_ERR_RAID_DIFF_STRIPES = ERR_RAID_DIFF_STRIPES,
DPT_ERR_RAID_DIFF_NUM_STR = ERR_RAID_DIFF_NUM_STR,
DPT_ERR_RAID_OVER_STRIPE = ERR_RAID_OVER_STRIPE,
DPT_ERR_RAID_COMP_REMOVE = ERR_RAID_COMP_REMOVE,
DPT_ERR_RAID_COMP_EMULATED = ERR_RAID_COMP_EMULATED,
DPT_ERR_RAID_COMP_DEVTYPE = ERR_RAID_COMP_DEVTYPE,
DPT_ERR_RAID_COMP_NON_512 = ERR_RAID_COMP_NON_512,
DPT_ERR_RAID_DIFF_BLOCKS = ERR_RAID_DIFF_BLOCKS,
DPT_ERR_RAID_DIFF_CAPACITY = ERR_RAID_DIFF_CAPACITY,
DPT_ERR_RAID_DIFF_VENDOR = ERR_RAID_DIFF_VENDOR,
DPT_ERR_RAID_DIFF_PRODUCT = ERR_RAID_DIFF_PRODUCT,
DPT_ERR_RAID_DIFF_REVISION = ERR_RAID_DIFF_REVISION,
DPT_ERR_RAID_NOT_SUPPORTED = ERR_RAID_NOT_SUPPORTED,
DPT_ERR_RAID_INVALID_HBA = ERR_RAID_INVALID_HBA,
DPT_ERR_RAID_TABLE_REQUIRED = ERR_RAID_TABLE_REQUIRED,
DPT_ERR_RAID_COMP_TAG = ERR_RAID_COMP_TAG,
DPT_ERR_RAID_MAX_ARRAYS = ERR_RAID_MAX_ARRAYS,
DPT_ERR_RAID_COMP_SIZE = ERR_RAID_COMP_SIZE,
DPT_ERR_RAID_FW_LEVEL = ERR_RAID_FW_LEVEL,
DPT_ERR_INVALID_HBA_ADDR = ERR_INVALID_HBA_ADDR,
DPT_ERR_ISA_ADDR_ONLY = ERR_ISA_ADDR_ONLY,
DPT_ERR_PRIMARY_HBA_EXISTS = ERR_PRIMARY_HBA_EXISTS,
DPT_ERR_NO_MORE_SLOTS = ERR_NO_MORE_SLOTS,
DPT_ERR_DUP_ISA_ADDR = ERR_DUP_ISA_ADDR,
DPT_ERR_DUP_EISA_SLOT = ERR_DUP_EISA_SLOT,
DPT_ERR_PRIMARY_ISA_ADDR = ERR_PRIMARY_ISA_ADDR,
DPT_ERR_SECONDARY_ISA_ADDR = ERR_SECONDARY_ISA_ADDR,
DPT_ERR_ABS_NO_MORE_IDS = ERR_ABS_NO_MORE_IDS,
DPT_ERR_ABS_NON_ZERO_LUN = ERR_ABS_NON_ZERO_LUN,
DPT_ERR_ABS_ADDR_LIMITS = ERR_ABS_ADDR_LIMITS,
DPT_ERR_ABS_ADDR_OCCUPIED = ERR_ABS_ADDR_OCCUPIED,
DPT_ERR_ABS_NO_MORE_LUNS = ERR_ABS_NO_MORE_LUNS,
DPT_ERR_NEW_ARTIFICIAL = ERR_NEW_ARTIFICIAL,
DPT_ERR_IO_NOT_SUPPORTED = ERR_IO_NOT_SUPPORTED,
DPT_ERR_RW_EXCEEDS_CAPACITY = ERR_RW_EXCEEDS_CAPACITY,
DPT_ERR_DATA_IN_OUT = ERR_DATA_IN_OUT,
DPT_ERR_SCSI_CMD_FAILED = ERR_SCSI_CMD_FAILED,
DPT_ERR_ARTIFICIAL_IO = ERR_ARTIFICIAL_IO,
DPT_ERR_SCSI_IO = ERR_SCSI_IO,
DPT_ERR_BLINK_LED_IO = ERR_BLINK_LED_IO,
DPT_ERR_OSD_MEM_ALLOC = ERR_OSD_MEM_ALLOC,
DPT_ERR_FORMATTING = ERR_FORMATTING,
DPT_ERR_HBA_BUSY = ERR_HBA_BUSY,
DPT_ERR_HBA_INITIALIZING = ERR_HBA_INITIALIZING,
DPT_ERR_DEL_OLD_RAID = ERR_DEL_OLD_RAID,
DPT_ERR_ENABLE_NEW_RAID = ERR_ENABLE_NEW_RAID,
DPT_ERR_UPDATE_OS_CONFIG = ERR_UPDATE_OS_CONFIG,
DPT_ERR_SCSI_ADDR_BOUNDS = ERR_SCSI_ADDR_BOUNDS,
DPT_ERR_SCSI_ADDR_CONFLICT = ERR_SCSI_ADDR_CONFLICT,
DPT_ERR_CANNOT_DELETE = ERR_CANNOT_DELETE,
DPT_ERR_FWD_NO_SPACE = ERR_FWD_NO_SPACE,
DPT_ERR_FWD_NOT_RESERVED = ERR_FWD_NOT_RESERVED,
DPT_ERR_FWD_NOT_INITIALIZED = ERR_FWD_NOT_INITIALIZED,
DPT_ERR_FWD_BLK_MISMATCH = ERR_FWD_BLK_MISMATCH,
DPT_ERR_FWD_BLK_OVERFLOW = ERR_FWD_BLK_OVERFLOW,
DPT_ERR_RSV_REMOVABLE = ERR_RSV_REMOVABLE,
DPT_ERR_RSV_NOT_DASD = ERR_RSV_NOT_DASD,
DPT_ERR_RSV_NON_ZERO = ERR_RSV_NON_ZERO,
DPT_ERR_RSV_HBA_UNABLE = ERR_RSV_HBA_UNABLE,
DPT_ERR_RSV_OTHER = ERR_RSV_OTHER,
DPT_ERR_SCAN_PHYSICALS = ERR_SCAN_PHYSICALS,
DPT_ERR_INIT_PHYSICALS = ERR_INIT_PHYSICALS,
DPT_ERR_SCAN_LOGICALS = ERR_SCAN_LOGICALS,
DPT_ERR_INIT_LOGICALS = ERR_INIT_LOGICALS,
DPT_ERR_COMM_XMIT_BUFFER = ERR_COMM_XMIT_BUFFER,
DPT_ERR_COMM_RCVE_BUFFER = ERR_COMM_RCVE_BUFFER,
DPT_ERR_COMM_DISCONNECTED = ERR_COMM_DISCONNECTED,
DPT_ERR_COMM_DATA_OVERFLOW = ERR_COMM_DATA_OVERFLOW,
DPT_ERRC_T_OPEN = ERRC_T_OPEN,
DPT_ERRC_T_BIND = ERRC_T_BIND,
DPT_ERRC_T_ALLOC = ERRC_T_ALLOC,
DPT_ERRC_T_CONNECT = ERRC_T_CONNECT,
DPT_ERRC_T_LISTEN = ERRC_T_LISTEN,
DPT_ERRC_T_ACCEPT = ERRC_T_ACCEPT,
DPT_ERRC_COMM_NW_INIT = ERRC_COMM_NW_INIT,
DPT_ERRC_COMM_WS_INIT = ERRC_COMM_WS_INIT,
DPT_ERRC_SEMAPHORE_TIMEOUT = ERRC_SEMAPHORE_TIMEOUT,
DPT_ERRC_CONNECTION_TAG = ERRC_CONNECTION_TAG,
DPT_ERRC_NOT_NULL_TERMED = ERRC_NOT_NULL_TERMED,
DPT_ERRC_MEM_ALLOC = ERRC_MEM_ALLOC,
DPT_ERRC_NULL_IO_BUFFER = ERRC_NULL_IO_BUFFER,
DPT_ERRC_INVALID_PASSWORD = ERRC_INVALID_PASSWORD,
DPT_ERRC_NOT_LOGGED_IN = ERRC_NOT_LOGGED_IN,
DPT_ERRC_ENGINE_LOAD = ERRC_ENGINE_LOAD,
DPT_ERRC_NOT_SUPPORTED = ERRC_NOT_SUPPORTED,
DPT_ERRC_ICRS_ACTIVE = ERRC_ICRS_ACTIVE,
DPT_ERRC_ICRS_INACTIVE = ERRC_ICRS_INACTIVE,
DPT_ERRC_ICRS_REQ_POSTED = ERRC_ICRS_REQ_POSTED,
DPT_ERRC_ICRS_THREAD_START = ERRC_ICRS_THREAD_START,
DPT_ERRC_ICRS_START_REQUEST = ERRC_ICRS_START_REQUEST,
DPT_ERRC_ICRS_INIT = ERRC_ICRS_INIT,
DPT_ERRC_ACCEPTING_ICR = ERRC_ACCEPTING_ICR,
DPT_ERRC_TX_MSG_SYNC = ERRC_TX_MSG_SYNC,
DPT_ERRC_RX_MSG_ACK = ERRC_RX_MSG_ACK,
DPT_ERRC_RX_MSG_HEADER = ERRC_RX_MSG_HEADER,
DPT_ERRC_TX_MSG_HEADER = ERRC_TX_MSG_HEADER,
DPT_ERRC_TX_TO_ENG_DATA = ERRC_TX_TO_ENG_DATA,
DPT_ERRC_RX_TO_ENG_DATA = ERRC_RX_TO_ENG_DATA,
DPT_ERRC_RX_STATUS_HEADER = ERRC_RX_STATUS_HEADER,
DPT_ERRC_TX_STATUS_HEADER = ERRC_TX_STATUS_HEADER,
DPT_ERRC_RX_FROM_ENG_DATA = ERRC_RX_FROM_ENG_DATA,
DPT_ERRC_TX_FROM_ENG_DATA = ERRC_TX_FROM_ENG_DATA,
DPT_ERRC_FROM_ENG_SIZE = ERRC_FROM_ENG_SIZE,
DPT_ERRC_TO_ENG_SIZE = ERRC_TO_ENG_SIZE,
DPT_ERRC_SERIAL_INIT = ERRC_SERIAL_INIT,
DPT_ERRC_BAUD_RATE = ERRC_BAUD_RATE,
DPT_ERRC_COMM_BUSY = ERRC_COMM_BUSY,
DPT_ERRC_INVALID_PROTOCOL = ERRC_INVALID_PROTOCOL,
DPT_ERRC_PORT_CONFLICT = ERRC_PORT_CONFLICT,
DPT_ERRC_MODEM_INIT = ERRC_MODEM_INIT,
DPT_ERRC_DIAL_ABORT = ERRC_DIAL_ABORT,
DPT_ERRC_DIAL_TIMEOUT = ERRC_DIAL_TIMEOUT,
DPT_ERRC_DIAL_BUSY = ERRC_DIAL_BUSY,
DPT_ERRC_DIAL_BEEPER_OK = ERRC_DIAL_BEEPER_OK,
DPT_ERRC_DIAL_UNEXPECTED_CD = ERRC_DIAL_UNEXPECTED_CD,
DPT_ERRC_DIAL_NO_TONE = ERRC_DIAL_NO_TONE,
DPT_ERRC_DIAL_NO_ANSWER = ERRC_DIAL_NO_ANSWER,
DPT_ERRC_DIAL_ERROR = ERRC_DIAL_ERROR,
DPT_ERRC_NEGOTIATION = ERRC_NEGOTIATION,
DPT_ERRC_MSG_TIMEOUT = ERRC_MSG_TIMEOUT,
DPT_ERRC_USER_ABORT = ERRC_USER_ABORT,
DPT_ERRSPX_RD_PROPERTY = ERRSPX_RD_PROPERTY,
DPT_ERRSPX_SAP = ERRSPX_SAP,
DPT_ERRC_SOCKET_ALLOC = ERRC_SOCKET_ALLOC,
DPT_ERRC_SOCKET_BIND = ERRC_SOCKET_BIND,
DPT_ERRC_SOCKET_ACCEPT = ERRC_SOCKET_ACCEPT,
DPT_ERRC_SOCKET_CONNECT = ERRC_SOCKET_CONNECT,
DPT_ERRC_USER_VALIDATION = ERRC_USER_VALIDATION,
DPT_ERR_FLASH_ERASE = ERR_FLASH_ERASE,
DPT_ERR_FLASH_SWITCH_MODES = ERR_FLASH_SWITCH_MODES,
DPT_ERR_FLASH_WRITE_512 = ERR_FLASH_WRITE_512,
DPT_ERR_FLASH_ENG_VERIFY = ERR_FLASH_ENG_VERIFY,
DPT_ERR_FLASH_INIT_REQ = ERR_FLASH_INIT_REQ,
DPT_ERR_EXCLUSION_TIME = ERR_EXCLUSION_TIME,
DPT_ERR_DIAG_SCHEDULED = ERR_DIAG_SCHEDULED,
DPT_ERR_DIAG_NOT_ACTIVE = ERR_DIAG_NOT_ACTIVE,
DPT_ERR_ELOG_NOT_LOADED = ERR_ELOG_NOT_LOADED,
DPT_ERR_ELOG_LOADED = ERR_ELOG_LOADED,
DPT_ERR_ELOG_EVENTS = ERR_ELOG_EVENTS,
DPT_ERR_ELOG_PAUSED = ERR_ELOG_PAUSED,
DPT_ERR_ELOG_NOT_PAUSED = ERR_ELOG_NOT_PAUSED,
DPT_ERR_SLOG_INVALID_TIME = ERR_SLOG_INVALID_TIME,
DPT_ERR_SLOG_STAT_GROUP = ERR_SLOG_STAT_GROUP,
DPT_ERR_ALMS_ALREADY_LINKED = ERR_ALMS_ALREADY_LINKED,
DPT_ERR_ALMS_NOT_LINKED = ERR_ALMS_NOT_LINKED,
DPT_ERR_ALMS_INVALID_RESOURCE_TYPE = ERR_ALMS_INVALID_RESOURCE_TYPE
};
Dpt_Error( dpt_Error new_Err = DPT_CMD_ERR_NO_ERROR ): err( new_Err ) {}
Dpt_Error( int new_Err ): err( (dpt_Error) new_Err ) {}
Dpt_Error(const Dpt_Error &src)
{
err = src.err;
}
Dpt_Error &operator = ( int eng_Err )
{
err = (dpt_Error) eng_Err;
if( Is_Error() )
{
// _asm int 3;
}
return( *this );
}
Dpt_Error &operator = ( dpt_Error eng_Err )
{
err = eng_Err;
if( Is_Error() )
{
// _asm int 3;
}
return( *this );
}
Dpt_Error &operator |= ( int eng_Err )
{
if ( !Is_Error() )
{
err = (dpt_Error) eng_Err;
}
return( *this );
}
Dpt_Error &operator |= ( dpt_Error eng_Err )
{
if ( !Is_Error() )
{
err = eng_Err;
}
return( *this );
}
operator char *() const;
operator dpt_Error() const { return(err); }
bool operator==(dpt_Error e) const
{
return(err == e);
}
bool operator!=(dpt_Error e) const
{
return(err != e);
}
inline bool Success() const
{
return((bool) ((err == DPT_MSG_RTN_COMPLETED) || (err == DPT_CMD_ERR_NO_ERROR)));
}
inline bool Failure() const
{
return(!Success());
}
// we have two errors meaning "OK". Allow both to work.
bool Is_Error() const
{
#if !defined _DPT_NETWARE
return( !( err == DPT_MSG_RTN_COMPLETED || err == DPT_CMD_ERR_NO_ERROR ) );
#else
return((bool) !(err == DPT_MSG_RTN_COMPLETED || err == DPT_CMD_ERR_NO_ERROR));
#endif
}
private:
dpt_Error err;
};
Command();
virtual ~Command();
void Init_Engine(int scanHbasOnly = 0);
// This executes the command that this object represents. This returns a
// "String_List" object. The reason it returns this rather than printing
// to the screen is to allow the caller complete control over how the strings
// are given to the user (if at all).
// Note: The caller is responsible for deleting this String_List
// object!
virtual Dpt_Error execute( String_List **output ) = 0;
virtual Command &Clone() const = 0;
static DPT_EngineIO_C *engine;
protected:
DPT_TAG_T Get_Log_Component(
SCSI_Address &obj_Address,
int dev_Index,
bool *index_Found
);
DPT_TAG_T Get_Component(
DPT_TAG_T parent_Tag,
int dev_Index,
bool *index_Found,
get_Devs_Type *dev_Type
);
DPT_TAG_T Get_Log_Dev_by_Index(
int dev_Index,
bool retrieve_Hiddens, // like hot-spares
bool *index_Found,
int hba_Index = -1
);
DPT_TAG_T Get_Log_Dev_by_Address(
SCSI_Address &obj_Address,
bool retrieve_Hiddens, // like hot-spares
bool *obj_Found
);
DPT_TAG_T Get_Address_by_Index(
SCSI_Address &obj_Address,
int dev_Index,
bool *obj_Found,
get_Devs_Type *dev_Type
);
DPT_TAG_T Get_Dev_by_Index(
int hba_Index, // should be negative
// if unused (will index
// across all HBA's then)
int dev_Index,
bool *index_Found,
get_Devs_Type *dev_Type
);
DPT_TAG_T Get_HBA_by_Index(
int hba_Index,
bool *index_Found
);
#if DONT_USE_TILL_DEBUGGED
DPT_TAG_T Get_Dev_by_Index_Type_and_Mask(
get_Devs_Type dev_Type, // what kind of object
SCSI_Address &obj_Root, // used for scope limitation
get_Devs_Mask dev_Mask, // used for scope limitation
int dev_Index,
bool *index_Found
);
#endif
DPT_TAG_T Get_Dev_by_Address(
SCSI_Address &obj_Address,
get_Devs_Type *dev_Type, // Note: this is
// only physical
// types
bool *obj_Found
);
DPT_TAG_T Get_Dev_by_Address_and_Type(
get_Devs_Type dev_Type,
SCSI_Address &obj_Address,
bool *obj_Found
);
SCSI_Address DPT_Tag_to_Address( DPT_TAG_T tag, bool *tag_Valid );
void PrintRaidAddress(DPT_TAG_T raid_Tag, String_List *out);
char *Strip_Trailing_Whitespace (char *str);
char PrintAQuestion(char *str);
void MakeArrayOptimal(DPT_TAG_T arrayTag);
void Commit( DPT_TAG_T tag = (DPT_TAG_T)NULL, bool nobuild = (bool)false );
int EngineFindIDs(int flags, DPT_MSG_T message,
DPT_TAG_T devicetag, void *where,
uSHORT maxIDs);
private:
int Convert_Engine_Level( unsigned engine_Level )
{
// the engine level has physicals as the highest value,
// which limits the number of levels. We're converting
// the level to '0' == phys, and anything higher is another
// higher level.
return( 2 - engine_Level );
}
static int num_Instances;
DLL_HANDLE_T eng_Module_Handle;
};
/*** STATIC DATA ***/
/*** MACROS ***/
/*** PROTOTYPES ***/
/*** FUNCTIONS ***/
#endif
/*** END OF FILE ***/
|
JerrNeon/AndroidProject
|
core/src/main/java/com/jn/kiku/annonation/RefreshViewType.java
|
<reponame>JerrNeon/AndroidProject<gh_stars>0
package com.jn.kiku.annonation;
import androidx.annotation.IntDef;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import static com.jn.kiku.annonation.RefreshViewType.ALL;
import static com.jn.kiku.annonation.RefreshViewType.NONE;
import static com.jn.kiku.annonation.RefreshViewType.ONLY_LOADMORE;
import static com.jn.kiku.annonation.RefreshViewType.ONLY_REFRESH;
/**
* Author:Stevie.Chen Time:2019/8/20
* Class Comment:RecyclerView类型
*/
@IntDef({NONE, ONLY_REFRESH, ONLY_LOADMORE, ALL})
@Retention(RetentionPolicy.SOURCE)
public @interface RefreshViewType {
int ALL = 0;//刷新和加载更多都有
int NONE = 1;//纯列表不带刷新和加载更多
int ONLY_REFRESH = 2;//只有刷新
int ONLY_LOADMORE = 3;//只有加载更多
}
|
pinkgoldpeach/Ticketline
|
client/src/main/java/at/ac/tuwien/inso/ticketline/client/gui/controller/LoginController.java
|
package at.ac.tuwien.inso.ticketline.client.gui.controller;
import at.ac.tuwien.inso.ticketline.client.service.AuthService;
import at.ac.tuwien.inso.ticketline.client.exception.ServiceException;
import at.ac.tuwien.inso.ticketline.client.util.BundleManager;
import at.ac.tuwien.inso.ticketline.client.util.SpringFxmlLoader;
import at.ac.tuwien.inso.ticketline.client.util.StripePayment;
import at.ac.tuwien.inso.ticketline.dto.UserEventDto;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import org.controlsfx.control.NotificationPane;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import java.net.URL;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* Controller for the login window
*/
@Component
public class LoginController implements Initializable {
private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
@Autowired
private SpringFxmlLoader springFxmlLoader;
@Autowired
private AuthService authService;
@FXML
private TextField txtUsername;
@FXML
private PasswordField txtPassword;
@FXML
private Button btnLogin, btnExit;
@FXML
private ComboBox<Locale> cbLanguage;
@FXML
private Pane root;
@Autowired
private ContainerController containerController;
private NotificationPane notificationPane;
private final ImageView errorImage = new ImageView(new Image(LoginController.class.getResourceAsStream("/image/icon/warning.png")));
private boolean english = false;
/**
* {@inheritDoc}
*/
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
notificationPane = new NotificationPane(root.getChildren().get(0));
notificationPane.setId("error_login");
root.getChildren().clear();
root.getChildren().add(notificationPane);
cbLanguage.getItems().clear();
cbLanguage.getItems().addAll(BundleManager.getSupportedLocales());
cbLanguage.valueProperty().addListener((observable, oldValue, newValue) -> reinitLocale(newValue));
cbLanguage.getSelectionModel().select(resourceBundle.getLocale());
if((cbLanguage.getValue().toString()).equals("en")){
english = true;
}
}
/**
* Reinitializes the UI with the given locale.
*
* @param newValue the new value
*/
private void reinitLocale(Locale newValue) {
LocaleContextHolder.setLocale(newValue);
BundleManager.changeLocale(newValue);
btnExit.setText(BundleManager.getBundle().getString("generic.exit"));
btnLogin.setText(BundleManager.getBundle().getString("login.login"));
txtPassword.setPromptText(BundleManager.getBundle().getString("login.password"));
txtUsername.setPromptText(BundleManager.getBundle().getString("login.username"));
}
/**
* Triggered if the user hits the login button, logs in the user,
* approppriate error messages if connection failed or input is not valid
* @param event the event
*/
@FXML
private void handleLogin(ActionEvent event) {
UserEventDto loginEvent;
try {
loginEvent = this.authService.login(txtUsername.getText(), txtPassword.getText());
} catch (ServiceException e) {
LOGGER.error(e.getMessage());
notificationPane.show(BundleManager.getExceptionBundle().getString("error.connection"), errorImage);
return;
}
if (loginEvent.equals(UserEventDto.AUTH_FAILURE)) {
notificationPane.show(BundleManager.getExceptionBundle().getString("error.loginData"), errorImage);
return;
} else if(loginEvent.equals(UserEventDto.BLOCKED)){
notificationPane.show(BundleManager.getExceptionBundle().getString("error.loginBlocked"), errorImage);
return;
}
((Node) event.getSource()).setCursor(Cursor.WAIT);
Stage landingPageContainerStage = new Stage();
landingPageContainerStage.setScene(new Scene((Parent) springFxmlLoader.load("/gui/fxml/container.fxml")));
landingPageContainerStage.setResizable(false);
landingPageContainerStage.setTitle(BundleManager.getBundle().getString("app.name"));
landingPageContainerStage.getIcons().add(new Image(LoginController.class.getResourceAsStream("/image/ticketlineLogo.png")));
landingPageContainerStage.show();
if((cbLanguage.getValue().toString()).equals("en")){
english = true;
}
((Node) event.getSource()).setCursor(Cursor.DEFAULT);
Node source = (Node) event.getSource();
Stage stage = (Stage) source.getScene().getWindow();
stage.close();
containerController.loadCache();
}
/**
* Exits the application
*
* @param event the event
*/
@FXML
private void handleExit(ActionEvent event) {
((Stage) ((Node) event.getSource()).getScene().getWindow()).close();
}
public boolean isEnglish(){
return english;
}
}
|
mooshak-dcc/mooshak-2
|
src/main/java/pt/up/fc/dcc/mooshak/client/gadgets/diagrameditor/DiagramEditorPresenter.java
|
package pt.up.fc.dcc.mooshak.client.gadgets.diagrameditor;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.storage.client.Storage;
import com.google.gwt.storage.client.StorageMap;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import pt.up.fc.dcc.mooshak.client.events.EventManager;
import pt.up.fc.dcc.mooshak.client.gadgets.GadgetPresenter;
import pt.up.fc.dcc.mooshak.client.gadgets.Token;
import pt.up.fc.dcc.mooshak.client.gadgets.diagrameditor.DiagramEditorView.Presenter;
import pt.up.fc.dcc.mooshak.client.gadgets.programeditorobservations.ProgramObservationsView;
import pt.up.fc.dcc.mooshak.client.guis.enki.event.ResourceOnSuccessEvent;
import pt.up.fc.dcc.mooshak.client.services.EnkiCommandServiceAsync;
import pt.up.fc.dcc.mooshak.client.services.ParticipantCommandServiceAsync;
import pt.up.fc.dcc.mooshak.client.utils.Base64Coder;
import pt.up.fc.dcc.mooshak.client.widgets.OkCancelDialog;
import pt.up.fc.dcc.mooshak.shared.commands.EvaluationSummary;
import pt.up.fc.dcc.mooshak.shared.commands.MooshakValue;
import pt.up.fc.dcc.mooshak.shared.commands.TransactionQuota;
public class DiagramEditorPresenter extends GadgetPresenter<DiagramEditorView> implements Presenter {
private static final RegExp REGEX_ACCEPTED_SUBMISSION = RegExp.compile("^accepted\\s*", "mi");
private ProgramObservationsView observationsView;
private Date startDate = null;
private Date stopDate = null;
private String lastSubmissionJson = "";
private StorageMap storageMap = null;
public DiagramEditorPresenter(HandlerManager eventBus, ParticipantCommandServiceAsync rpcService,
EnkiCommandServiceAsync enkiService, DiagramEditorView view, Token token) {
super(eventBus, null, rpcService, enkiService, null, null, null, view, token);
this.view.setPresenter(this);
Storage storage = Storage.getLocalStorageIfSupported();
if (storage != null) {
String prefix = contextInfo.getactivityId() + "." + problemId + "." + contextInfo.getParticipantId();
storageMap = new StorageMap(storage);
if (storageMap.containsKey(prefix + ".code")) {
view.importGraphAsJson(new String(Base64Coder.decodeLines(storageMap.get(prefix + ".code"))));
}
}
}
@Override
public void go(HasWidgets container) {
getAvailableLanguages();
}
/**
* @param observationsView
* the observationsView to set
*/
public void setObservationsView(ProgramObservationsView observationsView) {
this.observationsView = observationsView;
}
@Override
public void setObservations(String obs) {
observationsView.setObservations(obs);
}
/**
* Send a program for remote evaluation with data collected from the view
*
* @param consider
* this submission for evaluation
*/
public void onDiagramEvaluate(final boolean consider) {
Date now = new Date();
if (stopDate != null && now.after(stopDate)) {
observationsView.setObservations("Contest has ended");
return;
}
if (startDate != null && now.before(startDate)) {
observationsView.setObservations("Contest has not started yet");
return;
}
String message = consider ? ICPC_MESSAGES.submitDiagramConfirmation(problemId)
: ICPC_MESSAGES.validateDiagramConfirmation(problemId);
new OkCancelDialog(message) {
}.addDialogHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
lastSubmissionJson = view.getGraphAsJSON();
participantService.evaluate("diagram.json", lastSubmissionJson.getBytes(), problemId, new ArrayList<String>(),
consider, new AsyncCallback<Void>() {
@Override
public void onSuccess(Void result) {
EventManager.getInstance().refresh();
observationsView.setObservations(ICPC_CONSTANTS.processing());
if (consider)
getSubmissionsTransactionsData();
}
@Override
public void onFailure(Throwable caught) {
observationsView.setObservations(caught.getMessage());
if (consider)
getSubmissionsTransactionsData();
view.decreaseProgramWaitingEvaluation();
}
});
observationsView.setObservations(ICPC_CONSTANTS.submitted());
view.increaseProgramWaitingEvaluation();
}
});
}
public void update(final String submissionId, final boolean consider) {
LOGGER.info("Updating:" + submissionId);
participantService.getEvaluationSummary(submissionId, consider, new AsyncCallback<EvaluationSummary>() {
@Override
public void onFailure(Throwable caught) {
observationsView.setObservations("Error:" + caught.getMessage());
}
@Override
public void onSuccess(EvaluationSummary result) {
// TODO: On receive EvaluationSummary
view.decreaseProgramWaitingEvaluation();
if (consider) {
syncSubmissionResult(submissionId);
if (REGEX_ACCEPTED_SUBMISSION.test(result.getObservations())) {
getOnSuccessResource();
}
}
observationsView.clearObservations();
observationsView.addStatus(result.getStatus());
observationsView.addObservations(result.getObservations());
view.importGraphDiff(result.getFeedback());
}
});
}
private void syncSubmissionResult(String submissionId) {
enkiService.syncSubmissionResult(contextInfo.getactivityId(), resourceId, submissionId, new AsyncCallback<Void>() {
@Override
public void onFailure(Throwable t) {
Logger.getLogger("").log(Level.SEVERE, t.getMessage());
EventManager.getInstance().refresh();
}
@Override
public void onSuccess(Void arg0) {
EventManager.getInstance().refresh();
}
});
}
public void setContestDates(Date startDate, Date stopDate) {
this.startDate = startDate;
this.stopDate = stopDate;
}
@Override
public void getSubmissionsTransactionsData() {
participantService.getTransactionsData("submissions", new AsyncCallback<TransactionQuota>() {
@Override
public void onFailure(Throwable caught) {
view.setSubmitTooltip(-1, -1);
}
@Override
public void onSuccess(TransactionQuota result) {
if (result == null)
return;
view.setSubmitTooltip(result.getTransactionsLimit() - result.getTransactionsUsed(),
result.getTimeToReset());
}
});
}
/**
* Sends event requesting the resource to show on successful submission of
* an exercise
*/
private void getOnSuccessResource() {
eventBus.fireEvent(new ResourceOnSuccessEvent(contextInfo.getactivityId(), resourceId));
}
/**
* Get the languages available from the contest
*/
private void getAvailableLanguages() {
participantService.getAvailableLanguages(new AsyncCallback<Map<String, String>>() {
@Override
public void onFailure(Throwable caught) {
// ignore silently
Logger.getLogger("").log(Level.SEVERE, caught.getMessage());
}
@Override
public void onSuccess(Map<String, String> result) {
view.setLanguages(result);
}
});
}
@Override
public void revertToLastSubmission() {
view.importGraphAsJson(lastSubmissionJson);
}
public void replaceSubmissionContent(String id, String team) {
participantService.getSubmissionContent(id, team,
new AsyncCallback<MooshakValue>() {
@Override
public void onFailure(Throwable caught) {
observationsView.setObservations("Could not set submission contents");
}
@Override
public void onSuccess(MooshakValue result) {
view.importGraphAsJson(new String(result.getContent()));
}
});
}
@Override
public void saveToLocalStorage(String jsonGraph) {
if (storageMap != null) {
String prefix = contextInfo.getactivityId() + "." + problemId + "." + contextInfo.getParticipantId();
storageMap.put(prefix + ".code", Base64Coder.encodeString(jsonGraph));
}
}
}
|
uprm-gaming/virtual-factory
|
src/com/virtualfactory/threads/UpdateSlotsStorage.java
|
package com.virtualfactory.threads;
import com.jme3.math.Vector3f;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Box;
import com.virtualfactory.engine.GameEngine;
import com.virtualfactory.entity.E_Slot;
import com.virtualfactory.entity.E_Station;
import com.virtualfactory.utils.Pair;
import com.virtualfactory.utils.SlotStatus;
import com.virtualfactory.utils.TypeElements;
import java.util.Map;
/**
*
* @author David
*/
public class UpdateSlotsStorage extends Thread{
private Map<Integer, E_Station> mapUserStorageStation;
private GameEngine gameEngine;
@Override
public void run(){
E_Slot[][] matrixValue;
Box partBox;
Geometry part;
// System.out.println("-- Start UpdateSlotsStorage.. Thread:" + currentThread().getName());
// int slotsCleaned = 0;
for(E_Station station : mapUserStorageStation.values()){
matrixValue = station.getMatrixValue();
Pair<Pair<Integer,Integer>,Pair<Integer,Integer>> slot = null;
for (int i=0; i<matrixValue.length; i++){
for (int j=0; j<matrixValue[i].length; j++){
if (matrixValue[i][j].getSlotStatus().equals(SlotStatus.Free) || matrixValue[i][j].getSlotStatus().equals(SlotStatus.Unavailable)){
if (!station.getMatrix()[i][j].equals(0)){
slot = (Pair<Pair<Integer,Integer>,Pair<Integer,Integer>>)station.getMatrix()[i][j];
part = (Geometry)gameEngine.jmonkeyApp.getRootNode().getChild(TypeElements.STATION.toString() + station.getIdStation() + "_"
+ TypeElements.PART.toString() + slot.getFirst().getFirst() + "_" + slot.getFirst().getSecond());
partBox = (Box)part.getMesh();
if (partBox.getYExtent() > 0){
partBox.updateGeometry(new Vector3f(partBox.getCenter().getX(), 0, partBox.getCenter().getZ()), partBox.getXExtent(), 0, partBox.getZExtent());
// slotsCleaned++;
}
}
}
}
}
}
// System.out.println("-- End UpdateSlotsStorage: SlotsCleaned = " + slotsCleaned);
}
public Map<Integer, E_Station> getMapUserStorageStation() {
return mapUserStorageStation;
}
public void setMapUserStorageStation(Map<Integer, E_Station> mapUserStorageStation) {
this.mapUserStorageStation = mapUserStorageStation;
}
public GameEngine getGameEngine() {
return gameEngine;
}
public void setGameEngine(GameEngine gameEngine) {
this.gameEngine = gameEngine;
}
}
|
Tony031218/OI
|
local/codes/1132.cpp
|
/*************************************************************
* > File Name : 1132.cpp
* > Author : Tony
* > Created Time : 2019/08/09 12:18:47
* > Algorithm : 模拟
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0; int f = 1; char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();}
while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();}
return x * f;
}
const int maxn = 2010;
int n, m, ans;
char s[maxn][maxn];
int rnk[maxn], nxt[maxn];
int main() {
n = read(); m = read();
for (int i = 1; i <= n; ++i) {
scanf("%s", s[i] + 1);
}
for (int j = 1; j <= m; ++j) {
bool del = false;
nxt[1] = 0;
for (int i = 1; i < n; ++i) {
if (rnk[i] < rnk[i + 1]) {
nxt[i + 1] = nxt[i] + 1;
continue;
} else {
if (s[i][j] > s[i + 1][j]) {
ans++;
del = true;
break;
} else if (s[i][j] == s[i + 1][j]) {
nxt[i + 1] = nxt[i];
} else {
nxt[i + 1] = nxt[i] + 1;
}
}
}
if (!del) {
for (int i = 1; i <= n; ++i) {
rnk[i] = nxt[i];
}
}
}
printf("%d\n", ans);
return 0;
}
|
upupming/algorithm
|
leetcode/contest-40/5559.cpp
|
<filename>leetcode/contest-40/5559.cpp
#include <vector>
using namespace std;
// 最长单调子序列算法
// 数据量 10^3 比较小,可以直接用 dp O(n^2) 的算法,不需要用 O(n log n) 的贪心
// f[k]: 以 k 结尾的最长上升子序列的长度
// g[k]: 以 k 开头的最长上升子序列的长度
// argmax f[k] + g[k] - 1, st. f[k] > 1, g[k] > 1
class Solution {
public:
int minimumMountainRemovals(vector<int>& nums) {
vector<int> f(nums.size(), 1), g(nums.size(), 1);
for (int i = 1; i < nums.size(); i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j])
f[i] = max(f[i], f[j] + 1);
}
}
for (int i = nums.size() - 2; i >= 0; i--) {
for (int j = nums.size() - 1; j > i; j--) {
if (nums[i] > nums[j])
g[i] = max(g[i], g[j] + 1);
}
}
int maxCnt = 0;
for (int i = 0; i < nums.size(); i++) {
// cout << f[i] << ", " << g[i] << ", " << f[i] + g[i] - 1 << endl;
// 必须有坡
if (f[i] > 1 && g[i] > 1) {
maxCnt = max(maxCnt, f[i] + g[i] - 1);
}
}
return nums.size() - maxCnt;
}
};
|
LAOMENGA/LiteOS_Lab
|
iot_link/os/novaos/core/mem/src/heap.c
|
/*
* Copyright (c) [2019] Huawei Technologies Co.,Ltd.All rights reserved.
*
* LiteOS NOVA is licensed under the Mulan PSL v1.
* You can use this software according to the terms and conditions of the Mulan PSL v1.
* You may obtain a copy of Mulan PSL v1 at:
*
* http://license.coscl.org.cn/MulanPSL
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v1 for more details.
*/
#include <string.h>
#include <config.h>
#include <heap.h>
#include <phys_mem.h>
#include <errno.h>
#include <class.h>
#include <init.h>
#include <warn.h>
#include <bug.h>
#ifdef CONFIG_CMDER
#include <cmder.h>
#endif
#ifdef CONFIG_SYSCALL
#include <syscall.h>
#endif
/* globals */
heap_t kernel_heap [1] = {0,};
/*
* classes are defined as an array with only 1 element, so we can use it as an
* pointer
*/
class_t heap_class [1];
static inline void __put_chunk (heap_t * heap, chunk_t * chunk)
{
#ifdef CONFIG_HEAP_DEBUG
/* chunk size not aligned */
BUG_ON (chunk->size & ALLOC_ALIGN_MASK, "chunk size not aligned!");
memset (chunk + 1, 0xfe, chunk->size - sizeof (chunk_t));
#endif
__cm_put_chunk (&heap->cm, chunk);
#ifdef CONFIG_MEM_STATISTICS
__stat_chunk_add (&heap->stat, chunk);
#endif
}
static inline void __del_chunk (heap_t * heap, chunk_t * chunk)
{
#ifdef CONFIG_HEAP_DEBUG
/* chunk size not aligned */
BUG_ON (chunk->size & ALLOC_ALIGN_MASK, "chunk size not aligned!");
#endif
__cm_del_chunk (&heap->cm, chunk);
#ifdef CONFIG_MEM_STATISTICS
__stat_chunk_del (&heap->stat, chunk);
#endif
}
static inline chunk_t * __get_chunk (heap_t * heap, size_t size)
{
chunk_t * chunk = __cm_get_chunk (&heap->cm, size);
if (likely (chunk != NULL))
{
__del_chunk (heap, chunk);
#ifdef CONFIG_HEAP_DEBUG
memset (__get_mem_block (chunk), 0xac, chunk->size - sizeof (ach_t));
#endif
}
return chunk;
}
/**
* heap_init - initialize a heap struct
* @heap: the given heap
*
* return: 0 on success, negtive value on error
*/
int heap_init (heap_t * heap)
{
WARN_ON (heap == NULL,
errno = ERRNO_HEAP_ILLEGAL_ID; return -1,
"Invalid heap id!");
return obj_init (heap_class, &heap->obj);
}
/**
* heap_create - create a heap struct
* @heap: the given heap
*
* return: the created heap, NULL on error
*/
heap_id heap_create (void)
{
/*
* obj is just the first member of heap, so we can return this even when
* obj_open return NULL
*/
return container_of (obj_create (heap_class), heap_t, obj);
}
/**
* heap_destroy - destroy a heap
* @sem: the semaphore to be destroied
*
* return: 0 on success, negtive value on error
*/
int heap_destroy (heap_t * heap)
{
WARN_ON (heap == NULL,
errno = ERRNO_HEAP_ILLEGAL_ID; return -1,
"Invalid heap id!");
return obj_destroy (heap_class, &heap->obj);
}
static int __heap_add (heap_t * heap, char * buff, size_t size)
{
block_t * cb;
chunk_t * chunk, * last;
if (unlikely (mutex_lock (&heap->mux) != 0))
{
return -1;
}
/*
* this block of memory will be initialized as:
*
* +----+-----+-----+-----+
* | CB | ACH | FCH | ACH |
* +----+-----+-----+-----+
*
* CB - chunk block
* ACH - allocated chunk header
* FCH - free chunk header
*
* These two ACH at the beginning and ending are guards.
*/
cb = (block_t *) (buff);
cb->size = size;
cb->next = heap->blocks;
heap->blocks = cb;
chunk = (chunk_t *) (cb + 1);
chunk->prev = NULL;
chunk->size = sizeof (ach_t);
__set_chunk_allocated (chunk);
chunk = __get_next_chunk (chunk);
chunk->prev = (chunk_t *) (cb + 1);
chunk->size = (size - sizeof (block_t) - 2 * sizeof (ach_t));
__put_chunk (heap, chunk);
last = __get_next_chunk (chunk);
last->prev = chunk;
last->size = sizeof (ach_t);
__set_chunk_allocated (last);
(void) mutex_unlock (&heap->mux);
return 0;
}
/**
* heap_add - add a block of memory to a heap
* @heap: the heap to add in
* @buff: the memory address to add
* @size: the memory block size
*
* return: 0 on success, negtive value on error
*/
int heap_add (heap_t * heap, char * buff, size_t size)
{
char * end;
int ret;
WARN_ON (heap == NULL,
errno = ERRNO_HEAP_ILLEGAL_ID; return -1,
"Invalid heap id!");
WARN_ON (buff == NULL,
errno = ERRNO_HEAP_ILLEGAL_BLOCK; return -1,
"Invalid buffer!");
WARN_ON ((uintptr_t) buff > ((uintptr_t) buff + (uintptr_t) size),
errno = ERRNO_HEAP_ILLEGAL_BLOCK; return -1,
"Invalid buffer!");
end = buff + size;
buff = (char *) round_up (buff, ALLOC_ALIGN);
size = (size_t) round_down (end, ALLOC_ALIGN) - (size_t) buff;
WARN_ON (size < MIN_BLOCK_SIZE,
errno = ERRNO_HEAP_ILLEGAL_BLOCK; return -1,
"Invalid buffer");
if (unlikely (obj_verify_protect (heap_class, &heap->obj) != 0))
{
return -1;
}
#ifdef MAX_CHUNK_SIZE
ret = -1;
while (size >= MIN_BLOCK_SIZE)
{
size_t s = size > MAX_CHUNK_SIZE ? MAX_CHUNK_SIZE : size;
if (__heap_add (heap, buff, s) != 0)
{
break;
}
ret = 0;
size -= s;
buff += s;
}
#else
ret = __heap_add (heap, buff, size);
#endif
obj_unprotect (&heap->obj);
return ret;
}
/**
* __carve_extra - round up a block of memory and carve the unused memory at
* the beginning and ending
* @heap: the heap used
* @chunk: the chunk which hold the memory block to round up and carve
* @align: the alignment to round up
*
* return: the new aligned memory block
*/
static inline char * __carve_extra (heap_t * heap, chunk_t * chunk,
size_t align, size_t size)
{
char * mem = __get_mem_block (chunk);
char * aligned_mem = (char *) round_up (mem, align);
ach_t * ach = (ach_t *) chunk;
chunk_t * next;
uintptr_t usable_size;
uintptr_t carved_size;
#ifdef CONFIG_HEAP_DEBUG
/* memory not aligned */
BUG_ON ((uintptr_t) mem & ALLOC_ALIGN_MASK, "memory not aligned!");
#endif
if (aligned_mem != mem)
{
/*
* carve at the begining (carve head)
*
* .-chunk(FCH)-.
* / \
* +---+---+---+---+~~~+---+---+~~
* | p | s | l | ~ | p | s |
* | r | i | i | ~ | r | i |
* | e | z | s | ~ | e | z |
* | v | e | t | ~ | v | e |
* +---+---+---+---+~~~+---+---+~~
* \ \ /\
* `-- mem `-ach-' `-- aligned_mem
*
* now "mem != aligned_mem", so there must be "chunk < ach" so there are
* memory space in front of ach (chunk ~ ach), if "(ach - chunk) <= chunk",
* needless create new chunk, it is not worse to add logic save such memory
* block, because for any method to save such memory block we must allocate
* a chunk head for it, the chunk head itself waste more memory
*/
if ((size_t) (aligned_mem - (char *) chunk) < sizeof (chunk_t) + sizeof (ach_t))
{
__set_ach_to_mem (aligned_mem, chunk);
}
else
{
ach = (ach_t *) (aligned_mem - sizeof (ach_t));
carved_size = (uintptr_t) ach - (uintptr_t) chunk;
ach->prev = chunk;
ach->size = chunk->size - carved_size;
__get_next_chunk ((chunk_t *) ach)->prev = (chunk_t *) ach;
chunk->size = carved_size;
__put_chunk (heap, chunk);
}
}
/*
* carve at the ending (carve tail)
*
* there may be small memory gap (less than a chunk head size) betwen
* __get_mem_block (chunk) and mem, see above "carve head" for details
*
* .-- total size is chunk->size
* /
* ..................+....................
* / \
* +-----+-----+----------------------------+------------+ ~ ...
* | ACH | GAP | usable memory | next chunk | ~ ...
* +-----+-----+----------------------------+------------+ ~ ...
* \ \
* \ `-------- mem
* `-------------------- chunk
*
* so, the usable memory size is (chunk->size - (addr (mem) - (addr) chunk))
*
* we are going to carve extra memory block at the end of the usable memory
*/
usable_size = ach->size - (uintptr_t) (aligned_mem - (char *) ach);
carved_size = usable_size - size;
/*
* if the extra memory at the end is smaller than a chunk head size, do not
* create new chunk, extra memory size is now saved in carved_size
*/
if (carved_size >= sizeof (chunk_t))
{
/*
* there is extra memory at the end of usable memory greater than chunk size:
*
* .----- usable memory
* /
* .........+........
* / \
* / .- size \
* / / \
* .......+...... \
* / \ \
* +-----+-----+----------------+-----------+------------+ ~ ...
* | ACH | GAP | wanted memory | extra mem | next chunk | ~ ...
* +-----+-----+----------------+-----------+------------+ ~ ...
* \ \ \
* \ \ `-- extra memory at the end
* \ `------------------- mem
* `------------------------------ ach
*
* ==>
*
* +-----+-----+----------------+-----+-----+------------+ ~ ...
* | ACH | GAP | wanted memory | FCH | mem | next chunk | ~ ...
* +-----+-----+----------------+-----+-----+------------+ ~ ...
* \ \ \
* \ \ `--- new_chunk, will return to heap
* \ `------------------- mem, will return to user
* `------------------------------ ach
*/
ach->size -= carved_size;
chunk = (chunk_t *) (aligned_mem + size);
chunk->prev = (chunk_t *) ach;
chunk->size = carved_size;
next = __get_next_chunk (chunk);
next->prev = chunk;
__put_chunk (heap, chunk);
}
#ifdef CONFIG_MEM_STATISTICS
__stat_chunk_alloc (&heap->stat, (chunk_t *) ach);
#endif
__set_chunk_allocated ((chunk_t *) ach);
return aligned_mem;
}
/**
* heap_alloc_align - allocate a block of memory from a heap with alignment
* @heap: the heap to allocate from
* @bytes: size of memory in bytes to allocate
* @align: the expected alignment value
*
* return: the allocated memory block or NULL if fail
*/
char * heap_alloc_align (heap_t * heap, size_t align, size_t bytes)
{
chunk_t * chunk;
char * mem = NULL;
WARN_ON (heap == NULL,
errno = ERRNO_HEAP_ILLEGAL_ID; return NULL,
"Invalid heap id!");
/* align must be power of 2 */
WARN_ON (align & (align - 1),
errno = ERRNO_HEAP_ILLEGAL_ALIGN; return NULL,
"Invalid alignment!");
align = unlikely (align < ALLOC_ALIGN) ? ALLOC_ALIGN : align;
/* ALLOC_MIN_SIZE is defined as sizeof (dlist_t) */
bytes = unlikely (bytes < ALLOC_MIN_SIZE) ? ALLOC_MIN_SIZE
: round_up (bytes, ALLOC_ALIGN);
if (unlikely (obj_verify_protect (heap_class, &heap->obj) != 0))
{
return NULL;
}
if (likely (mutex_lock (&heap->mux) == 0))
{
/* find a big enough memory chunk */
chunk = __get_chunk (heap, bytes + sizeof (ach_t) + align - ALLOC_ALIGN);
if (chunk != NULL)
{
mem = __carve_extra (heap, chunk, align, bytes);
}
(void) mutex_unlock (&heap->mux);
}
obj_unprotect (&heap->obj);
WARN_ON (mem == NULL,
errno = ERRNO_HEAP_NOT_ENOUGH_MEMORY,
"Not enough memory!");
return mem;
}
/**
* heap_alloc - allocate a block of memory from a heap
* @heap: the heap to allocate from
* @bytes: size of memory in bytes to allocate
*
* return: the allocated memory block or NULL if fail
*/
char * heap_alloc (heap_t * heap, size_t bytes)
{
return heap_alloc_align (heap, ALLOC_ALIGN, bytes);
}
/**
* heap_free - free a block of memory
* @heap: the heap to allocate from
*
* return: NA
*/
void heap_free (heap_t * heap, char * mem)
{
chunk_t * chunk;
chunk_t * prev_chunk;
chunk_t * next_chunk;
WARN_ON (heap == NULL,
errno = ERRNO_HEAP_ILLEGAL_ID; return,
"Invalid heap id!");
/* ANSI C - free of NULL is OK */
if (unlikely (mem == NULL))
{
return;
}
if (unlikely (obj_verify_protect (heap_class, &heap->obj) != 0))
{
return;
}
if (likely (mutex_lock (&heap->mux) == 0))
{
chunk = (chunk_t *) __get_ach_from_mem (mem);
__set_chunk_free (chunk);
#ifdef CONFIG_MEM_STATISTICS
__stat_chunk_free (&heap->stat, chunk);
#endif
prev_chunk = __get_prev_chunk (chunk);
next_chunk = __get_next_chunk (chunk);
if (__is_free (prev_chunk))
{
__del_chunk (heap, prev_chunk);
prev_chunk->size += chunk->size;
chunk = prev_chunk;
}
if (__is_free (next_chunk))
{
__del_chunk (heap, next_chunk);
chunk->size += next_chunk->size;
next_chunk = __get_next_chunk (chunk);
}
next_chunk->prev = chunk;
__put_chunk (heap, chunk);
mutex_unlock (&heap->mux);
}
obj_unprotect (&heap->obj);
}
static char * __realloc (heap_t * heap, char * ptr, size_t size)
{
char * mem;
size_t usable_size;
size_t left_size;
chunk_t * chunk;
chunk_t * new;
chunk_t * next;
chunk = (chunk_t *) __get_ach_from_mem (ptr);
next = __get_next_chunk (chunk);
usable_size = (size_t) (((char *) next) - ptr);
if (usable_size < size)
{
mem = heap_alloc (heap, size);
if (mem != NULL)
{
memcpy (mem, ptr, usable_size);
heap_free (heap, ptr);
}
return mem;
}
/* memory in this chunk is enough, needless alloc new one */
left_size = usable_size - size;
if (left_size < sizeof (chunk_t))
{
return ptr;
}
/* extra memory in the end and can be released */
new = (chunk_t *) ((char *) next - left_size);
new->prev = chunk;
if (mutex_lock (&heap->mux) != 0)
{
return ptr;
}
chunk->size -= left_size;
if (__is_free (next))
{
new->size = left_size + next->size;
__del_chunk (heap, next);
next = __get_next_chunk (new);
}
else
{
new->size = left_size;
}
next->prev = new;
__put_chunk (heap, new);
(void) mutex_unlock (&heap->mux);
return ptr;
}
/**
* heap_realloc - realloc memory from a heap
* @heap: the heap to allocate from
* @ptr: the original memory
* @size: the new size
*
* return: the allocated memory block or NULL if fail
*/
char * heap_realloc (heap_t * heap, char * ptr, size_t size)
{
WARN_ON (heap == NULL,
errno = ERRNO_HEAP_ILLEGAL_ID; return NULL,
"Invalid heap id!");
if (ptr == NULL)
{
return heap_alloc (heap, size);
}
if (size == 0)
{
heap_free (heap, ptr);
return NULL;
}
if (size < ALLOC_MIN_SIZE)
{
size = ALLOC_MIN_SIZE;
}
else
{
size = round_up (size, ALLOC_ALIGN);
}
if (unlikely (obj_verify_protect (heap_class, &heap->obj) != 0))
{
return NULL;
}
ptr = __realloc (heap, ptr, size);
obj_unprotect (&heap->obj);
return ptr;
}
#ifdef CONFIG_MEM_STATISTICS
int heap_stat_get (heap_t * heap, mem_stat_t * stat)
{
WARN_ON (heap == NULL,
errno = ERRNO_HEAP_ILLEGAL_ID; return -1,
"Invalid heap id!");
WARN_ON (stat == NULL,
errno = ERRNO_HEAP_ILLEGAL_STAT; return -1,
"Invalid stat!");
if (unlikely (obj_verify_protect (heap_class, &heap->obj) != 0))
{
return -1;
}
if (likely (mutex_lock (&heap->mux) == 0))
{
*stat = heap->stat;
stat->max_free_size = __get_max_free (&heap->cm);
mutex_unlock (&heap->mux);
}
obj_unprotect (&heap->obj);
return 0;
}
#endif
static int __heap_init (obj_id obj, va_list valist)
{
heap_id heap = container_of (obj, heap_t, obj);
memset (heap, 0, sizeof (heap_t));
if (unlikely (__cm_init (&heap->cm) != 0))
{
return -1;
}
return mutex_init (&heap->mux);
}
static int __heap_destroy (obj_id obj)
{
heap_id heap = container_of (obj, heap_t, obj);
block_t * block = heap->blocks;
/* check if there is any busy blocks in the heap */
while (block)
{
/* get the first chunk and skip the first ACH */
chunk_t * chunk = __get_next_chunk ((chunk_t *) (block + 1));
do
{
/* reach last one */
if (unlikely (chunk->size == (sizeof (ach_t) | 1)))
{
break;
}
if (unlikely (!__is_free (chunk)))
{
return -1;
}
chunk = __get_next_chunk (chunk);
} while (1);
block = block->next;
}
if (unlikely (mutex_destroy (&heap->mux) != 0))
{
return -1;
}
return 0;
}
/**
* heap_lib_init - heap library initialization routine
*
* return: 0 on success, negtive value on error
*/
static int heap_lib_init (void)
{
const struct phys_mem * spm = system_phys_mem;
int block_added = 0;
BUG_ON (class_init (heap_class, MID_HEAP, sizeof (heap_t),
__heap_init, __heap_destroy, NULL, NULL) != 0,
"fail to initialize heap_class!");
BUG_ON (heap_init (kernel_heap) != 0, "fail to initialize kernel_heap!");
while (spm->end)
{
if (heap_add (kernel_heap, spm->start, (size_t) (spm->end - spm->start)) == 0)
{
block_added++;
}
spm++;
}
BUG_ON (block_added == 0, "no block added!");
return 0;
}
MODULE_INIT (kernel, heap_lib_init);
#ifdef CONFIG_SYSCALL
static const uintptr_t syscall_entries_heap [] =
{
(uintptr_t) heap_create,
(uintptr_t) heap_add,
(uintptr_t) heap_alloc,
(uintptr_t) heap_alloc_align,
(uintptr_t) heap_free,
(uintptr_t) heap_realloc,
#ifdef CONFIG_MEM_STATISTICS
(uintptr_t) heap_stat_get,
#endif
};
const struct syscall_table syscall_table_heap =
{
ARRAY_SIZE (syscall_entries_heap),
syscall_entries_heap
};
#endif
#ifdef CONFIG_CMDER
static inline void __dump_block (cmder_t * cmder, block_t * block)
{
chunk_t * chunk = (chunk_t *) (block + 1);
cmder_printf (cmder, "\taddress size status\n");
cmder_printf (cmder, "\t---------- ---------- ---------\n");
do
{
cmder_printf (cmder, "\t%10p %10p %s", chunk, chunk->size & ~1u,
(chunk->size & 1) == 0 ? "free\n" : "allocated\n");
if ((chunk->prev != NULL) && (chunk->size == (sizeof (ach_t) | 1)))
{
break;
}
chunk = __get_next_chunk (chunk);
} while (1);
}
static void __cmd_dump_heap (cmder_t * cmder, heap_t * heap, bool show_chunk)
{
block_t * block = heap->blocks;
if (show_chunk)
{
cmder_printf (cmder, "\tchunk information:\n\n");
}
if (mutex_lock (&heap->mux) != 0)
{
return;
}
if (show_chunk)
{
while (block)
{
__dump_block (cmder, block);
block = block->next;
}
}
#ifdef CONFIG_MEM_STATISTICS
cmder_printf (cmder, "\n\tSUMMARY:\n\n");
cmder_printf (cmder, "\tstatus bytes blocks\n");
cmder_printf (cmder, "\t------ ------------------ ------\n");
cmder_printf (cmder, "\tcurrent:\n");
cmder_printf (cmder, "\tfree\t%-18p %d\n", heap->stat.free_size, heap->stat.free_chunks);
cmder_printf (cmder, "\talloc\t%-18p %d\n", heap->stat.busy_size, heap->stat.busy_chunks);
cmder_printf (cmder, "\tcumulative:\n");
cmder_printf (cmder, "\tfree\t0x%-16llx %d\n", heap->stat.cum_size_freed, heap->stat.cum_freed);
cmder_printf (cmder, "\talloc\t0x%-16llx %d\n", heap->stat.cum_size_allocated, heap->stat.cum_allocated);
cmder_printf (cmder, "\n\tmaximum allocated size ever: %p\n", heap->stat.max_busy_size);
cmder_printf (cmder, "\n\tmaximum free size: %p\n", __get_max_free (&heap->cm));
#endif
mutex_unlock (&heap->mux);
}
static int __cmd_meminfo (cmder_t * cmder, int argc, char * argv [])
{
const struct phys_mem * spm = system_phys_mem;
bool show_chunk = false;
int i;
for (i = 1; i < argc; i++)
{
if (strncmp (argv [i], "--chunk", 7) == 0)
{
show_chunk = true;
}
}
cmder_printf (cmder, "all physcial memory blocks:\n\n");
cmder_printf (cmder, "address end length \n");
cmder_printf (cmder, "---------- ---------- ----------\n");
while (spm->end)
{
cmder_printf (cmder, "%10p %10p %10p\n", spm->start, spm->end - 1,
spm->end - spm->start);
spm++;
}
cmder_printf (cmder, "\n[kernel_heap] statistics\n\n");
(void) __cmd_dump_heap (cmder, kernel_heap, show_chunk);
return 0;
}
CMDER_CMD_DEF ("meminfo", "show memory information, usage: 'meminfo [--chunk]'",
__cmd_meminfo);
#endif
|
libogonek/ogonek
|
include/ogonek/encoding/iterator.h++
|
<reponame>libogonek/ogonek
// Ogonek
//
// Written in 2012-2013 by <NAME> <<EMAIL>>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
// Encoding/decoding iterators
#ifndef OGONEK_ENCODING_ITERATOR_HPP
#define OGONEK_ENCODING_ITERATOR_HPP
#include <ogonek/traits.h++>
#include <ogonek/types.h++>
#include <ogonek/error.h++>
#include <ogonek/detail/constants.h++>
#include <ogonek/detail/ranges.h++>
#include <ogonek/detail/container/partial_array.h++>
#include <ogonek/detail/container/encoded_character.h++>
#include <boost/iterator/iterator_facade.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/range/sub_range.hpp>
#include <algorithm>
#include <array>
#include <initializer_list>
#include <cstddef>
namespace ogonek {
namespace detail {
class decoding_iterator_access;
} // namespace detail
template <typename EncodingForm, typename Iterator, typename ErrorHandler>
struct encoding_iterator
: boost::iterator_facade<
encoding_iterator<EncodingForm, Iterator, ErrorHandler>,
CodeUnit<EncodingForm>,
std::forward_iterator_tag, // TODO
CodeUnit<EncodingForm>
> {
public:
encoding_iterator(Iterator first, Iterator last)
: first(std::move(first)), last(std::move(last)) { encode_next(); }
CodeUnit<EncodingForm> dereference() const {
return encoded[current];
}
bool equal(encoding_iterator const& that) const {
return (first == that.first && current == that.current)
|| (first == last && that.first == that.last
&& current == depleted && that.current == depleted);
}
void increment() {
++current;
if(current == encoded.size()) {
encode_next();
}
}
private:
static constexpr std::size_t depleted = -1;
void encode_next() {
if(first != last) {
auto u = *first++;
encoded = encode_validated(u, ErrorHandler{});
current = 0;
} else {
current = depleted;
}
}
detail::encoded_character<EncodingForm> encode_validated(code_point u, assume_valid_t) {
return EncodingForm::encode_one(u, state, assume_valid);
}
template <typename ErrorHandler1>
detail::encoded_character<EncodingForm> encode_validated(code_point u, ErrorHandler1) {
if(u > detail::last_code_point || detail::is_surrogate(u)) {
return ErrorHandler1::template apply_encode<EncodingForm>(u, state);
} else {
return EncodingForm::encode_one(u, state, ErrorHandler1{});
}
}
Iterator first, last;
EncodingState<EncodingForm> state {};
detail::encoded_character<EncodingForm> encoded {};
std::size_t current;
};
template <typename EncodingForm, typename Iterator, typename ErrorHandler>
struct decoding_iterator
: boost::iterator_facade<
decoding_iterator<EncodingForm, Iterator, ErrorHandler>,
code_point,
std::forward_iterator_tag, // TODO
code_point
> {
public:
decoding_iterator(Iterator first, Iterator last)
: first(std::move(first)), last(std::move(last)) {}
code_point dereference() const {
code_point u;
auto s = state;
EncodingForm::decode_one(boost::sub_range<range>(first, last), u, s, ErrorHandler{});
return u;
}
bool equal(decoding_iterator const& that) const {
return first == that.first || (first == last && that.first == that.last);
}
void increment() {
code_point dummy;
first = EncodingForm::decode_one(boost::sub_range<range>(first, last), dummy, state, ErrorHandler{}).begin();
}
private:
using range = boost::iterator_range<Iterator>;
friend class detail::decoding_iterator_access;
Iterator first, last;
EncodingState<EncodingForm> state {};
};
} // namespace ogonek
#endif // OGONEK_ENCODING_ITERATOR_HPP
|
jojoba106/OpenPype
|
openpype/hosts/harmony/plugins/load/load_template_workfile.py
|
<gh_stars>10-100
import tempfile
import zipfile
import os
import shutil
from avalon import api, harmony
class ImportTemplateLoader(api.Loader):
"""Import templates."""
families = ["harmony.template", "workfile"]
representations = ["*"]
label = "Import Template"
def load(self, context, name=None, namespace=None, data=None):
# Import template.
temp_dir = tempfile.mkdtemp()
zip_file = api.get_representation_path(context["representation"])
template_path = os.path.join(temp_dir, "temp.tpl")
with zipfile.ZipFile(zip_file, "r") as zip_ref:
zip_ref.extractall(template_path)
sig = harmony.signature("paste")
func = """function %s(args)
{
var template_path = args[0];
var drag_object = copyPaste.pasteTemplateIntoGroup(
template_path, "Top", 1
);
}
%s
""" % (sig, sig)
harmony.send({"function": func, "args": [template_path]})
shutil.rmtree(temp_dir)
subset_name = context["subset"]["name"]
return harmony.containerise(
subset_name,
namespace,
subset_name,
context,
self.__class__.__name__
)
def update(self, container, representation):
pass
def remove(self, container):
pass
class ImportWorkfileLoader(ImportTemplateLoader):
"""Import workfiles."""
families = ["workfile"]
representations = ["zip"]
label = "Import Workfile"
|
equalitie/baskerville
|
src/baskerville/db/data_partitioning.py
|
<reponame>equalitie/baskerville<gh_stars>10-100
# Copyright (c) 2020, eQualit.ie inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import dateutil.parser
from datetime import datetime
from baskerville.db.base import GeneratorBase, TEMPLATE_FOLDER
from baskerville.db.temporal_partition import TemporalPartitionedTable, \
TimePeriod
from baskerville.util.enums import PartitionByEnum
from jinja2 import Environment, FileSystemLoader
class DataPartitioner(GeneratorBase):
"""
Base partitioner, generates the data that the partitioning template needs
"""
def __init__(
self,
parent_table,
partition_field,
index_by=None,
template_path=TEMPLATE_FOLDER,
template_name='data_partitioning.jinja2'
):
super().__init__(
template_path=template_path, template_name=template_name
)
self.parent_table = parent_table
self.partition_field = partition_field
self.index_by = index_by
self.partitions = []
def to_dict(self):
return self.__dict__
class TemporalDataPartitioner(DataPartitioner):
"""
Partition data based on a date field. Generates
"""
def __init__(
self,
partitioned_table_name,
partition_field,
time_window,
strict=False,
partition_by=PartitionByEnum.w,
index_by=None,
template_path=TEMPLATE_FOLDER,
template_name='data_partitioning.jinja2'
):
"""
Partitions the parent table by a time period, e.g. w for per week
partitions, m for per month partitions.
:param str partitioned_table_name: the name of the parent table
:param str partition_field: the name of the field to partition by
:param baskerville.db.base.TimePeriod time_window: the period to
partition data for, e.g. a year, starting from 1-1-2018 to 31-12-2018
:param str split_by: w for week, m for month
:param index_by: list of fields to index the partitions by
"""
super().__init__(
partitioned_table_name,
partition_field,
index_by=index_by,
template_path=template_path,
template_name=template_name,
)
self.strict = strict
self.partitioned_table = TemporalPartitionedTable(
partitioned_table_name,
time_window,
partition_field,
partitioned_by=partition_by,
index_by=index_by,
strict=self.strict
)
self.partitions = self.partitioned_table.partition()
def to_dict(self):
return self.partitioned_table.to_dict()
class AlphabeticalDataPartitioner(DataPartitioner):
partition_by = list('abcdefghijklmnopqrtsuvwxyz')
class RangeDataPartitioner(DataPartitioner):
pass
def get_temporal_partitions(conf):
"""
Given the database configuration, construct the sql to be executed to
partition a table (set in the configuration) by dates, using a
TemporalDataPartitioner
:param dict[str, T] conf: the dict representation of the database
configuration
:return: The string representation of the sql to be executed to partition
a table by a time period.
"""
from datetime import date
since = conf['data_partition']['since']
until = conf['data_partition']['until']
if isinstance(since, date):
since = datetime(*since.timetuple()[:6])
if isinstance(until, date):
until = datetime(*until.timetuple()[:6])
return str(TemporalDataPartitioner(
conf['partition_table'],
conf['partition_field'],
time_window=TimePeriod(
since,
until
),
partition_by=conf['partition_by'],
index_by=conf['data_partition']['index_by'],
template_path=conf['template_folder'] or TEMPLATE_FOLDER,
template_name=conf['data_partition']['template']
)
)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'parentname', help='The name of the table to be partitioned'
)
parser.add_argument('field', help='The table field to partition by')
parser.add_argument(
'ptype', help='The type of data partitioner, e.g. temporal'
)
parser.add_argument(
'-s', '--since', help='Optional', type=dateutil.parser.parse
)
parser.add_argument(
'-u', '--until', help='The type of data partitioner',
type=dateutil.parser.parse
)
parser.add_argument(
'-b', '--splitby', help='Split the data by week or month'
)
parser.add_argument('-st', '--strict', help='tbd', default=False)
parser.add_argument(
'-i', '--indexby', help='Index the data', dest='indexby',
type=lambda s: [str(item) for item in s.split(',')]
)
args = parser.parse_args()
if args.ptype == 'temporal':
if not args.since or not args.until or not args.splitby:
raise ValueError(
'Temporal partitioner needs since and until and splitby'
)
tp = TemporalDataPartitioner(
args.parentname,
args.field,
time_window=TimePeriod(args.since, args.until),
partition_by=args.splitby,
index_by=args.indexby
)
print(tp.partitions)
# Create the jinja2 environment - trim_blocks helps control whitespace.
j2_env = Environment(loader=FileSystemLoader(TEMPLATE_FOLDER),
trim_blocks=True)
# get template and render
template = j2_env.get_template("data_partitioning.jinja2")
template.globals['now'] = datetime.utcnow
rendered_data = template.render(tp.to_dict())
with open('test.sql', 'wb') as out_file:
out_file.write(bytes(rendered_data.encode('utf-8')))
# https://stackoverflow.com/a/23206636/3433323
|
Arainsd/Wms
|
src/Mobiles/Ionic/www/js/ngTygaSoft/services/LocalStorage.js
|
<filename>src/Mobiles/Ionic/www/js/ngTygaSoft/services/LocalStorage.js
angular.module('ngTygaSoft.services.LocalStorage', [])
//本地存储数据===================================
.factory('$tygasoftLocalStorage', ['$window', function ($window) {
return {
//存储单个属性
Set: function (key, value) {
$window.localStorage[key] = value;
},
//读取单个属性
Get: function (key, defaultValue) {
return $window.localStorage[key] || defaultValue;
},
//存储对象,以JSON格式存储
SetObject: function (key, value) {
$window.localStorage[key] = JSON.stringify(value);
},
//读取对象
GetObject: function (key) {
return JSON.parse($window.localStorage[key] || '{}');
}
}
}]);
|
MammatusTech/qbit-microservices-examples
|
serviceBundle/src/main/java/com/mammatustech/todo/Auditor.java
|
package com.mammatustech.todo;
interface Auditor {
void audit(final String operation, final String log);
}
|
kittqiu/snippet-fibula
|
www/model/train/train_resource.js
|
<reponame>kittqiu/snippet-fibula
'use strict';
var base = require('../_base');
module.exports = function(warp){
return base.defineModel(warp, 'TrainResource', [
base.column_id('section_id', {index:true}),
base.column_id('course_id', {index:true}),
base.column_id('att_id')
], {
table: 'train_resource'
});
};
|
vipulchodankar/gec-computer-engineering
|
first-year/semester-2/Practicals/Experiment 9/insertend.c
|
<filename>first-year/semester-2/Practicals/Experiment 9/insertend.c<gh_stars>1-10
#include<stdio.h>
int main(){
int num,arr[100],i,val;
printf("Enter number of elements:\n");
scanf("%d",&num);
printf("\nEnter %d Elements:\n",num);
for(i=0;i<num;i++)
scanf("%d",&arr[i]);
printf("\nEnter element to be inserted at the end:\n");
scanf("%d",&val);
arr[num]=val;
printf("\nFinal Array: \n");
for(i=0;i<=num;i++)
printf("%d ",arr[i]);
printf("\n\n");
}
|
AnkushChandra/Os-simulator
|
routes/executables/system_calls/man.c
|
<reponame>AnkushChandra/Os-simulator
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
// Usage man systemcall
int main(int argc, char const *argv[])
{
if(strcmp(argv[1],"./man")==0)
{
if(strcmp(argv[2],"access")==0)
printf("Usage: access flag pathname\nFlags are: F_OK,R_OK,W_OK,X_OK\nUsed to check access permissions of the file.\n");
if(strcmp(argv[2],"creat")==0)
printf("Usage: creat pathname\nUsed to create files.\n");
if(strcmp(argv[2],"dup")==0)
printf("Usage: dup pathname\nUsed to create a duplicate file descriptor");
if(strcmp(argv[2],"link")==0)
printf("Usage: link old_pathname new_pathname\nUsed to create a link to an existing file.\n");
if(strcmp(argv[2],"unlink")==0)
printf("Usage: unlink pathname\nUsed to remove a file.\n");
if(strcmp(argv[2],"lseek")==0)
printf("Usage: lseek offset flag pathname\nFlags are: SEEK_END, SEEK_CUR, SEEK_SET.\nUsed to manipulate file pointer position.\n");
if(strcmp(argv[2],"man")==0)
printf("Usage: man systemcall\nUsed to read manual for systemcall.\n");
if(strcmp(argv[2],"open")==0)
printf("Usage:open pathname\nUsed to open a file.\n");
if(strcmp(argv[2],"read")==0)
printf("Usage: read no_of_bytes pathname\nUsed to read from a file.\n");
if(strcmp(argv[2],"write")==0)
printf("Usage: write pathname text_to_write\nUsed to write text to a file\n");
if(strcmp(argv[2],"getid")==0)
printf("Usage: getid\nUsed to obtain personal, group, process and parent process id.\n");
if(strcmp(argv[2],"kill")==0)
printf("Usage: kill pid\nUsed to send signal to a process.\n");
if(strcmp(argv[2],"fork")==0)
printf("Usage: fork no_of_calls\nUsed to create a child process.\n");
}
}
|
tengge1/bootstrap-es6
|
bootstrap-es6/bootstrap-es6/source/XType.js
|
// XType.js
class XType {
static get(config) {
if (config == null || config.xtype == null) {
throw 'XType: config or config.xtype is undefined.';
}
var cls = XType.xtypes[config.xtype];
if (cls == null) {
throw `XType: xtype '${config.xtype}' is undefined.`;
}
return new cls(config);
}
static add(name, cls) {
if (XType.xtypes[name] == null) {
XType.xtypes[name] = cls;
}
}
static remove(name) {
delete XType.xtypes[name];
}
}
XType.xtypes = {};
|
trivigy/migrate
|
types/direction.go
|
<reponame>trivigy/migrate
package types
import (
"bytes"
"github.com/trivigy/migrate/v2/global"
)
// Direction defines the type of the migration direction.
type Direction int
const (
// DirectionUp indicates the direction type is forward.
DirectionUp Direction = iota + 1
// DirectionDown indicates the direction type is backward (rollback).
DirectionDown
)
var (
directionUpStr = "up"
directionDownStr = "down"
)
func (r Direction) String() string {
return toStringDirection[r]
}
var toStringDirection = map[Direction]string{
Direction(0): global.UnknownStr,
DirectionUp: directionUpStr,
DirectionDown: directionDownStr,
}
// MarshalJSON marshals the enum as a quoted json string.
func (r Direction) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBufferString(`"`)
if _, err := buffer.WriteString(toStringDirection[r]); err != nil {
return nil, err
}
if _, err := buffer.WriteString(`"`); err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
|
ktrzeciaknubisa/jxcore-binary-packaging
|
lib/jx/_jx_argv.js
|
<filename>lib/jx/_jx_argv.js
// Copyright & License details are available under JXCORE_LICENSE file
var argvParsed = null;
var separators = ['=', ':'];
var prefixes = ['--', '-']; // maintain this order
if (process.platform === 'win32')
prefixes.push('/');
var path = require('path');
var fs = require('fs');
var jxSpecials = {
'install' : {
'expectMainModule' : false
},
'npm' : {
'expectMainModule' : false
},
'monitor' : {
'expectMainModule' : false
},
'package' : {
'expectMainModule' : true
},
'compile' : {
'expectMainModule' : true
},
'mt' : {
'expectMainModule' : true
},
'mt-keep' : {
'expectMainModule' : true
}
};
// encapsulation of single argument
var singleArg = function(arg, _index) {
var _this = this;
this.index = _index;
this.org = arg;
this.name;
this.value;
// indicates if value was given for an arg, e.g. --arg=2 or -d 1 etc.
this.hasValue;
// one of [ "--", "-", "/"], e.g. --arg=2 or -d or /T
this.prefix;
// one of [ "=", ":", " "], e.g. --arg=2 or --arg:2 or -arg 2
this.valueSep;
this.isInt;
this.asInt;
this.isBool;
this.asBool;
this.setValue = function(_value) {
_this.value = _value;
var _int = parseInt(_value);
if (!isNaN(_int)) {
_this.isInt = true;
_this.asInt = _int;
}
var b = exports.isBoolValue(_value);
if (b.isFalse || b.isTrue) {
_this.isBool = true;
_this.asBool = b.isFalse ? false : true;
}
_this.hasValue = typeof _this.value !== 'undefined';
};
// splits value by a given separator (or exports.sep)
this.splitBySep = function(sep) {
sep = sep || exports.sep;
var arr = _this.value === undefined ? [] : _this.value.toString()
.split(sep);
var ret = [];
// copying non-empty parts
for (var a = 0, len = arr.length; a < len; a++) {
if (arr[a].trim())
ret.push(arr[a]);
}
return ret.length ? ret : null;
};
// checking if value is available after a separator within this argv,
// e.g. --arg=1 or --arg:2
var splitValue = function(_value) {
for (var a = 0, len = separators.length; a < len; a++) {
var separator = separators[a];
var sepId = _value.indexOf(separator);
if (sepId === -1) {
_this.name = _value;
} else {
_this.name = _value.slice(0, sepId);
_this.valueSep = separator;
_this.setValue(_value.slice(sepId + 1));
break;
}
}
};
var found = false;
for (var p = 0, len = prefixes.length; p < len; p++) {
var prefix = prefixes[p];
// checking if the arg is prefixed, e.g. --arg or -arg
if (arg.indexOf(prefix) === 0 && arg.indexOf(' ') === -1) {
found = true;
this.prefix = prefix;
arg = arg.slice(prefix.length);
splitValue(arg);
break;
}
}
if (!found)
this.name = arg;
};
// parses array of args (e.g. process.argv)
var argvParser = function(arr, options) {
var result = {};
var index = -1;
if (!options)
options = {};
var checkNextValue = function() {
if (!arr.length)
return;
var v = new singleArg(arr[0]);
if (v.prefix) {
// the next param is not a value, it is just another arg
v = null;
return;
} else {
arr.shift();
index++;
return v.org;
}
};
var addNoInternals = function(obj) {
if (!(obj instanceof singleArg))
return;
if (options.internals) {
if (options.internals.indexOf(obj.name) !== -1 ||
options.internals.indexOf((obj.prefix || '') + obj.name) !== -1)
return;
}
noInternals.push(obj.org);
if (obj.hasValue && obj.valueSep === ' ')
noInternals.push(obj.value);
};
var set = function(name, arg) {
if (!result[name] || options.overwrite)
result[name] = arg;
addNoInternals(arg);
};
var setExtra = function(name, obj) {
if (!result['_'])
result['_'] = {};
result['_'][name] = obj;
addNoInternals(obj);
};
// copy
var arr = arr.slice(0);
var noPrefix = [];
var noInternals = [];
var expectMainFileName = true;
var arg;
while (arg = arr.shift()) {
index++;
if (index === 0) {
noInternals.push(arg);
continue;
}
if (index === 1) {
// mt / mt-keep special treatments
if (arg.slice(0, 2) === 'mt') {
arg = '--' + arg;
if (arg.indexOf(':') === -1)
arg += ':2';
} else {
}
}
var _arg = new singleArg(arg, index);
// checking for special jx command and eventually mainModule file name in
// argv
if (expectMainFileName && !_arg.prefix) {
if (jxSpecials[_arg.name]) {
setExtra(_arg.name, true);
expectMainFileName = jxSpecials[_arg.name].expectMainModule;
} else {
expectMainFileName = false;
setExtra('mainModule', arg);
}
noInternals.push(arg);
continue;
}
if (_arg.prefix) {
if (options.splitSingleDashed && _arg.prefix === '-' &&
_arg.name.length > 1) {
// multiple params after single dash, like: -abc
var splitted = _arg.name.split('');
for (var o = 0, len = splitted.length; o < len; o++) {
set(splitted[o], new singleArg(splitted[o], index));
}
continue;
}
// regular params with values: -a 5 --name=value --name value
if (!_arg.hasValue) {
var val = checkNextValue();
if (val !== undefined) {
_arg.setValue(val);
_arg.valueSep = ' '; // space
}
}
set(_arg.name, _arg);
} else {
// params without leading dashes (- or --) are treated like values
_arg.setValue(_arg.name);
_arg.hasValue = false;
noPrefix.push(_arg.name);
set(_arg.name, _arg);
}
}
if (noPrefix.length)
setExtra('withoutPrefix', noPrefix);
setExtra('withoutInternals', noInternals);
return result;
};
// argv and options are optional
exports.parse = function(argv, options) {
if (Object.prototype.toString.call(argv) === '[object Array]') {
// argv is given
return argvParser(argv, options);
} else {
// argv is not given, so we'll parse process.argv
if (argv && Object.prototype.toString.call(argv) === '[object Object]') {
// argv is options
options = argv || {};
}
if (!options)
options = {};
if (argvParsed && !options.force)
return argvParsed;
argvParsed = argvParser(process.argv, options);
return argvParsed;
}
};
var getSep = function() {
if (!process.env.JX_ARG_SEP)
return ','; // default is comma
var sep = process.env.JX_ARG_SEP;
if (process.platform === 'win32') {
// windows needs stripping quotes if used, e.g.: set JX_ARG_SEP="@"
var first = sep.trim().slice(0, 1);
var last = sep.trim().slice(-1);
if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
sep = sep.trim(); // trimming before first quote and after last one
sep = sep.slice(1, sep.length - 1);
} else {
// if quotes are not used, unix would trim, so let's trim on windows too,
// e.g.:
// set JX_ARG_SEP=@ && echo ok
// (there are spaces after @)
sep = sep.trim();
}
}
return sep;
};
exports.sep = getSep();
// removes an arg and it's value if exists (alters process.argv!)
// returns true if arg was found and removed
// `arg` is expected to be entire name (including prefixes and value after : or
// =)
exports.remove = function(arg, expectValue) {
var cnt = 1;
var id = process.argv.indexOf(arg);
if (id === -1)
return false;
if (expectValue && process.argv[id + 1]) {
// if the next arg is a value for this arg (is not prefixed),
// remove it too, e.g. --arg value
var _arg = new singleArg(process.argv[id + 1]);
if (!_arg.prefix)
cnt++;
}
process.argv.splice(id, cnt);
return true;
};
exports.getValue = function(arg, defaultValue) {
if (!argvParsed)
exports.parse();
if (argvParsed[arg]) {
if (argvParsed[arg].value === undefined)
return defaultValue;
return argvParsed[arg].value;
} else
return defaultValue;
};
exports.getBoolValue = function(arg, defaultValue) {
if (!argvParsed)
exports.parse();
if (argvParsed[arg])
// even if !isBool, returns true, because the arg exists
return argvParsed[arg].isBool ? argvParsed[arg].asBool : true;
else
return !!defaultValue;
};
exports.isBoolValue = function(arg) {
if (typeof arg === 'undefined' || arg === null || !arg.toString())
return {
isFalse: false,
isTrue: false
};
var lc = arg.toString().toLowerCase();
return {
isFalse: (lc === 'no' || lc == 'false' || lc == '0'),
isTrue: (lc === 'yes' || lc == 'true' || lc == '1')
};
};
|
DaveVoorhis/Rel
|
ServerV0000/src/org/reldb/rel/v0/types/TypeRelation.java
|
package org.reldb.rel.v0.types;
import org.reldb.rel.v0.generator.Generator;
import org.reldb.rel.v0.values.*;
public class TypeRelation extends TypeHeading {
private static TypeRelation emptyType = new TypeRelation(new Heading());
/** Create new relation type from a given Heading. */
public TypeRelation(Heading heading) {
super(heading);
}
/** Get TABLE_DUM or TABLE_DEE relation type. */
public static TypeRelation getEmptyRelationType() {
return emptyType;
}
public Value getDefaultValue(Generator generator) {
return ValueRelation.getDum(generator);
}
public String getSignature() {
return "RELATION " + heading.getSignature();
}
}
|
ocl-vgu/jocl
|
src/main/java/com/vgu/se/jocl/expressions/AssociationClassCallExp.java
|
/**************************************************************************
Copyright 2019 Vietnamese-German-University
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@author: ngpbh
***************************************************************************/
package com.vgu.se.jocl.expressions;
import com.vgu.se.jocl.types.Class;
import com.vgu.se.jocl.types.Type;
import com.vgu.se.jocl.visit.ParserVisitor;;
public class AssociationClassCallExp extends NavigationCallExp {
private String referredAssociationEnd;
private Class referredAssociationClass;
private String oppositeAssociationEnd;
private Type oppositeAssociationEndType;
private Type referredAssociationEndType;
private String association;
public AssociationClassCallExp(Expression source,
String referredAssociationEnd) {
super.navigationSource = source;
this.referredAssociationEnd = referredAssociationEnd;
}
@Override
public void accept(ParserVisitor parserVisitor) {
parserVisitor.visit(this);
}
public String getReferredAssociationEnd() {
return referredAssociationEnd;
}
public void setReferredAssociationEnd(String referredAssociationEnd) {
this.referredAssociationEnd = referredAssociationEnd;
}
public Class getReferredAssociationClass() {
return referredAssociationClass;
}
public void setReferredAssociationClass(Class referredAssociationClass) {
this.referredAssociationClass = referredAssociationClass;
}
public String getOppositeAssociationEnd() {
return oppositeAssociationEnd;
}
public void setOppositeAssociationEnd(String oppositeAssociationEnd) {
this.oppositeAssociationEnd = oppositeAssociationEnd;
}
public Type getOppositeAssociationEndType() {
return oppositeAssociationEndType;
}
public void setOppositeAssociationEndType(Type oppositeAssociationEndType) {
this.oppositeAssociationEndType = oppositeAssociationEndType;
}
public Type getReferredAssociationEndType() {
return referredAssociationEndType;
}
public void setReferredAssociationEndType(Type referredAssociationEndType) {
this.referredAssociationEndType = referredAssociationEndType;
}
public String getAssociation() {
return association;
}
public void setAssociation(String association) {
this.association = association;
}
public void parseAssociationName() {
String leftType = referredAssociationEndType.getReferredType();
String rightType = oppositeAssociationEndType.getReferredType();
if(leftType.compareTo(rightType) > 0) {
this.association = String.format("%1$s_%2$s_%3$s_%4$s", rightType,
oppositeAssociationEnd, referredAssociationEnd, leftType);
} else {
this.association = String.format("%1$s_%2$s_%3$s_%4$s", leftType,
referredAssociationEnd, oppositeAssociationEnd, rightType);
}
}
}
|
chrilves/gospeak
|
infra/src/test/scala/gospeak/infra/services/storage/sql/CfpRepoSqlSpec.scala
|
package gospeak.infra.services.storage.sql
import cats.data.NonEmptyList
import gospeak.core.domain.Talk
import gospeak.core.domain.utils.FakeCtx
import gospeak.infra.services.storage.sql.CfpRepoSqlSpec._
import gospeak.infra.services.storage.sql.EventRepoSqlSpec.{table => eventTable}
import gospeak.infra.services.storage.sql.testingutils.RepoSpec
import gospeak.infra.services.storage.sql.testingutils.RepoSpec.mapFields
class CfpRepoSqlSpec extends RepoSpec {
describe("CfpRepoSql") {
it("should create and retrieve a cfp for a group") {
val (user, group, ctx) = createUserAndGroup().unsafeRunSync()
val talkId = Talk.Id.generate()
cfpRepo.findRead(cfpData1.slug).unsafeRunSync() shouldBe None
cfpRepo.list(params)(ctx).unsafeRunSync().items shouldBe Seq()
cfpRepo.availableFor(talkId, params).unsafeRunSync().items shouldBe Seq()
val cfp = cfpRepo.create(cfpData1)(ctx).unsafeRunSync()
cfpRepo.find(cfp.id).unsafeRunSync().get shouldBe cfp
cfpRepo.findRead(cfpData1.slug).unsafeRunSync().get shouldBe cfp
cfpRepo.list(params)(ctx).unsafeRunSync().items shouldBe Seq(cfp)
cfpRepo.availableFor(talkId, params).unsafeRunSync().items shouldBe Seq(cfp)
}
it("should fail to create a cfp when the group does not exists") {
val user = userRepo.create(userData1, now, None).unsafeRunSync()
val ctx = FakeCtx(now, user, group)
an[Exception] should be thrownBy cfpRepo.create(cfpData1)(ctx).unsafeRunSync()
}
it("should fail to create two cfp for a group") {
val (user, group, ctx) = createUserAndGroup().unsafeRunSync()
cfpRepo.create(cfpData1)(ctx).unsafeRunSync()
an[Exception] should be thrownBy cfpRepo.create(cfpData1)(ctx).unsafeRunSync()
}
it("should fail on duplicate slug") {
val (user, group1, ctx1) = createUserAndGroup().unsafeRunSync()
val group2 = groupRepo.create(groupData2)(ctx1).unsafeRunSync()
cfpRepo.create(cfpData1)(FakeCtx(now, user, group1)).unsafeRunSync()
an[Exception] should be thrownBy cfpRepo.create(cfpData1)(FakeCtx(now, user, group2)).unsafeRunSync()
}
describe("Queries") {
it("should build insert") {
val q = CfpRepoSql.insert(cfp)
check(q, s"INSERT INTO ${table.stripSuffix(" c")} (${mapFields(fields, _.stripPrefix("c."))}) VALUES (${mapFields(fields, _ => "?")})")
}
it("should build update") {
val q = CfpRepoSql.update(group.id, cfp.slug)(cfpData1, user.id, now)
check(q, s"UPDATE $table SET slug=?, name=?, begin=?, close=?, description=?, tags=?, updated_at=?, updated_by=? WHERE c.group_id=? AND c.slug=?")
}
it("should build selectOne for cfp id") {
val q = CfpRepoSql.selectOne(cfp.id)
check(q, s"SELECT $fields FROM $table WHERE c.id=? $orderBy")
}
it("should build selectOne for cfp slug") {
val q = CfpRepoSql.selectOne(cfp.slug)
check(q, s"SELECT $fields FROM $table WHERE c.slug=? $orderBy")
}
it("should build selectOne for group id and cfp slug") {
val q = CfpRepoSql.selectOne(group.id, cfp.slug)
check(q, s"SELECT $fields FROM $table WHERE c.group_id=? AND c.slug=? $orderBy")
}
it("should build selectOne for event id") {
val q = CfpRepoSql.selectOne(event.id)
check(q, s"SELECT $fields FROM $table INNER JOIN $eventTable ON c.id=e.cfp_id WHERE e.id=? $orderBy")
}
it("should build selectOne for cfp slug id and date") {
val q = CfpRepoSql.selectOneIncoming(cfp.slug, now)
check(q, s"SELECT $fields FROM $table WHERE (c.close IS NULL OR c.close > ?) AND c.slug=? $orderBy")
}
it("should build selectPage for a group") {
val q = CfpRepoSql.selectPage(params)
check(q, s"SELECT $fields FROM $table WHERE c.group_id=? $orderBy LIMIT 20 OFFSET 0")
}
it("should build selectPage for a talk") {
val q = CfpRepoSql.selectPage(talk.id, params)
check(q, s"SELECT $fields FROM $table WHERE c.id NOT IN (SELECT p.cfp_id FROM proposals p WHERE p.talk_id=?) $orderBy LIMIT 20 OFFSET 0")
}
it("should build selectAll for group id") {
val q = CfpRepoSql.selectAll(group.id)
check(q, s"SELECT $fields FROM $table WHERE c.group_id=? $orderBy")
}
it("should build selectAll for cfp ids") {
val q = CfpRepoSql.selectAll(NonEmptyList.of(cfp.id, cfp.id, cfp.id))
check(q, s"SELECT $fields FROM $table WHERE c.id IN (?, ?, ?) $orderBy")
}
it("should build selectAll for group and date") {
val q = CfpRepoSql.selectAllIncoming(group.id, now)
check(q, s"SELECT $fields FROM $table WHERE (c.close IS NULL OR c.close > ?) AND c.group_id=? $orderBy")
}
it("should build selectTags") {
val q = CfpRepoSql.selectTags()
check(q, s"SELECT c.tags FROM $table")
}
}
}
}
object CfpRepoSqlSpec {
val table = "cfps c"
val fields: String = mapFields("id, group_id, slug, name, begin, close, description, tags, created_at, created_by, updated_at, updated_by", "c." + _)
val orderBy = "ORDER BY c.close IS NULL, c.close DESC, c.name IS NULL, c.name"
}
|
systemfreund/teku
|
sync/src/main/java/tech/pegasys/teku/sync/CoalescingChainHeadChannel.java
|
<filename>sync/src/main/java/tech/pegasys/teku/sync/CoalescingChainHeadChannel.java<gh_stars>0
/*
* Copyright 2020 ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package tech.pegasys.teku.sync;
import java.util.Optional;
import org.apache.tuweni.bytes.Bytes32;
import tech.pegasys.teku.infrastructure.unsigned.UInt64;
import tech.pegasys.teku.storage.api.ChainHeadChannel;
import tech.pegasys.teku.storage.api.ReorgContext;
import tech.pegasys.teku.sync.SyncService.SyncSubscriber;
public class CoalescingChainHeadChannel implements ChainHeadChannel, SyncSubscriber {
private final ChainHeadChannel delegate;
private boolean syncing = false;
private Optional<PendingEvent> pendingEvent = Optional.empty();
public CoalescingChainHeadChannel(final ChainHeadChannel delegate) {
this.delegate = delegate;
}
public static ChainHeadChannel create(
final ChainHeadChannel delegate, final SyncService syncService) {
final CoalescingChainHeadChannel channel = new CoalescingChainHeadChannel(delegate);
syncService.subscribeToSyncChanges(channel);
return channel;
}
@Override
public synchronized void chainHeadUpdated(
final UInt64 slot,
final Bytes32 stateRoot,
final Bytes32 bestBlockRoot,
final boolean epochTransition,
final Optional<ReorgContext> optionalReorgContext) {
if (!syncing) {
delegate.chainHeadUpdated(
slot, stateRoot, bestBlockRoot, epochTransition, optionalReorgContext);
} else {
pendingEvent =
pendingEvent
.map(
current ->
current.update(
slot, stateRoot, bestBlockRoot, epochTransition, optionalReorgContext))
.or(
() ->
Optional.of(
new PendingEvent(
slot,
stateRoot,
bestBlockRoot,
epochTransition,
optionalReorgContext)));
}
}
@Override
public synchronized void onSyncingChange(final boolean isSyncing) {
syncing = isSyncing;
if (!syncing) {
pendingEvent.ifPresent(PendingEvent::send);
pendingEvent = Optional.empty();
}
}
private class PendingEvent {
private UInt64 slot;
private Bytes32 stateRoot;
private Bytes32 bestBlockRoot;
private boolean epochTransition;
private Optional<ReorgContext> reorgContext;
private PendingEvent(
final UInt64 slot,
final Bytes32 stateRoot,
final Bytes32 bestBlockRoot,
final boolean epochTransition,
final Optional<ReorgContext> reorgContext) {
this.slot = slot;
this.stateRoot = stateRoot;
this.bestBlockRoot = bestBlockRoot;
this.epochTransition = epochTransition;
this.reorgContext = reorgContext;
}
public void send() {
delegate.chainHeadUpdated(slot, stateRoot, bestBlockRoot, epochTransition, reorgContext);
}
public PendingEvent update(
final UInt64 slot,
final Bytes32 stateRoot,
final Bytes32 bestBlockRoot,
final boolean epochTransition,
final Optional<ReorgContext> reorgContext) {
this.slot = slot;
this.stateRoot = stateRoot;
this.bestBlockRoot = bestBlockRoot;
if (epochTransition) {
this.epochTransition = true;
}
if (reorgContext.isPresent() && hasEarlierCommonAncestor(reorgContext)) {
this.reorgContext = reorgContext;
}
return this;
}
private boolean hasEarlierCommonAncestor(final Optional<ReorgContext> reorgContext) {
return this.reorgContext.isEmpty()
|| reorgContext
.orElseThrow()
.getCommonAncestorSlot()
.isLessThan(this.reorgContext.orElseThrow().getCommonAncestorSlot());
}
}
}
|
weicao/galaxysql
|
polardbx-parser/src/test/java/com/alibaba/polardbx/druid/sql/parser/SQLStatementParserTest.java
|
/*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.polardbx.druid.sql.parser;
import com.alibaba.polardbx.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import org.junit.Assert;
import org.junit.Test;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class SQLStatementParserTest
{
@Test
public void testInsertFunction()
throws SQLException
{
MySqlStatementParser sqlStatementParser = new MySqlStatementParser("insert into batch_features_pb (id, url, feature) values(0, 'https://cbu01.alicdn.com/img/ibank/2013/441/486/1036684144_687583347.jpg', CLOTHES_FEATURE_EXTRACT_V1(url))");
sqlStatementParser.config(SQLParserFeature.InsertReader, true);
MyInsertValueHandler myInsertValueHandler = new MyInsertValueHandler();
sqlStatementParser.parseInsert();
sqlStatementParser.parseValueClause(myInsertValueHandler);
Assert.assertTrue(myInsertValueHandler.getFunctions().containsKey("CLOTHES_FEATURE_EXTRACT_V1"));
Assert.assertEquals("url",
myInsertValueHandler.getFunctions().get("CLOTHES_FEATURE_EXTRACT_V1"));
}
@Test
public void testInsertFunction2()
throws SQLException
{
MySqlStatementParser sqlStatementParser = new MySqlStatementParser("insert into batch_features_pb (id, url, feature) values(0, \"https://cbu01.alicdn.com/img/ibank/2013/441/486/1036684144_687583347.jpg\", CLOTHES_FEATURE_EXTRACT_V1(url))");
sqlStatementParser.config(SQLParserFeature.InsertReader, true);
MyInsertValueHandler myInsertValueHandler = new MyInsertValueHandler();
sqlStatementParser.parseInsert();
sqlStatementParser.parseValueClause(myInsertValueHandler);
Assert.assertTrue(myInsertValueHandler.getFunctions().containsKey("CLOTHES_FEATURE_EXTRACT_V1"));
Assert.assertEquals("url",
myInsertValueHandler.getFunctions().get("CLOTHES_FEATURE_EXTRACT_V1"));
}
@Test
public void testInsertFunctions()
throws SQLException
{
MySqlStatementParser sqlStatementParser = new MySqlStatementParser("insert into batch_features_pb (id, url, feature) values(0, 'https://cbu01.alicdn.com/img/ibank/2013/441/486/1036684144_687583347.jpg', CLOTHES_FEATURE_EXTRACT_V1(url), CLOTHES_ATTRIBUTE_EXTRACT_V1(url))");
sqlStatementParser.config(SQLParserFeature.InsertReader, true);
MyInsertValueHandler myInsertValueHandler = new MyInsertValueHandler();
sqlStatementParser.parseInsert();
sqlStatementParser.parseValueClause(myInsertValueHandler);
Assert.assertTrue(myInsertValueHandler.getFunctions().containsKey("CLOTHES_FEATURE_EXTRACT_V1"));
Assert.assertTrue(myInsertValueHandler.getFunctions().containsKey("CLOTHES_ATTRIBUTE_EXTRACT_V1"));
Assert.assertEquals("url",
myInsertValueHandler.getFunctions().get("CLOTHES_FEATURE_EXTRACT_V1"));
Assert.assertEquals("url",
myInsertValueHandler.getFunctions().get("CLOTHES_ATTRIBUTE_EXTRACT_V1"));
}
private class MyInsertValueHandler
implements SQLInsertValueHandler
{
private Map<String, Object> functions = new HashMap<String, Object>();
public Map<String, Object> getFunctions()
{
return functions;
}
@Override
public Object newRow()
throws SQLException
{
return null;
}
@Override
public void processInteger(Object row, int index, Number value)
throws SQLException
{
}
@Override
public void processString(Object row, int index, String value)
throws SQLException
{
}
@Override
public void processDate(Object row, int index, String value)
throws SQLException
{
}
@Override
public void processDate(Object row, int index, Date value)
throws SQLException
{
}
@Override
public void processTimestamp(Object row, int index, String value)
throws SQLException
{
}
@Override
public void processTimestamp(Object row, int index, Date value)
throws SQLException
{
}
@Override
public void processTime(Object row, int index, String value)
throws SQLException
{
}
@Override
public void processDecimal(Object row, int index, BigDecimal value)
throws SQLException
{
}
@Override
public void processBoolean(Object row, int index, boolean value)
throws SQLException
{
}
@Override
public void processNull(Object row, int index)
throws SQLException
{
}
@Override
public void processFunction(Object row, int index, String funcName, long funcNameHashCode64, Object... values)
throws SQLException
{
this.functions.put(funcName, values[0]);
}
@Override
public void processRow(Object row)
throws SQLException
{
}
@Override
public void processComplete()
throws SQLException
{
}
}
}
|
suchov/codewars-1
|
(4 kyu) Human readable duration format.js
|
/**
* Human readable duration format (4 kyu) https://www.codewars.com/kata/human-readable-duration-format
* Your task in order to complete this Kata is to write a function which
* formats a duration, given as a number of seconds, in a human-friendly way.
* The function must accept a non-negative integer. If it is zero, it just
* returns "now". Otherwise, the duration is expressed as a combination of
* years, days, hours, minutes and seconds.
* It is much easier to understand with an example:
* formatDuration(62) // returns "1 minute and 2 seconds"
* formatDuration(3662) // returns "1 hour, 1 minute and 2 seconds"
* Note that spaces are important.
* Detailed rules
* The resulting expression is made of components like 4 seconds, 1 year,
* etc. In general, a positive integer and one of the valid units of time,
* separated by a space. The unit of time is used in plural if the integer
* is greater than 1.
* The components are separated by a comma and a space (", "). Except the
* last component, which is separated by " and ", just like it would be
* written in English.
* A more significant units of time will occur before than a least
* significant one. Therefore, 1 second and 1 year is not correct, but 1
* year and 1 second is.
* Different components have different unit of times. So there is not
* repeated units like in 5 seconds and 1 second.
* A component will not appear at all if its value happens to be zero. Hence,
* 1 minute and 0 seconds is not valid, but it should be just 1 minute.
* A unit of time must be used "as much as possible". It means that the
* function should not return 61 seconds, but 1 minute and 1 second instead.
* Formally, the duration specified by of a component must not be greater
* than any valid more significant unit of time.
* For the purpose of this Kata, a year is 365 days and a day is 24 hours.
*/
function formatDuration (seconds) {
const pluralization = (x, y) => x ? `${x} ${y}${x > 1 ? 's' : ''}` : '';
const join = (x, y, z) => (x && y ? z ? ', ' : ' and ' : '') + y;
const sufix = ['year', 'day', 'hour', 'minute', 'second'];
const [y, d] = [seconds / 31536e3, (seconds / 864e2)%365]
.map((t, i) => pluralization(Math.floor(t), sufix[i]))
const [h, m, s] = new Date(1e3 * seconds)
.toISOString()
.substr(11, 8)
.split`:`
.map((t, i) => pluralization(+t, sufix[i + 2]));
return y + join(y, d, h) + join(d, h, m) + join(h, m, s) + join(m, s, false) || 'now';
}
|
uk-gov-mirror/ministryofjustice.cla_backend
|
cla_backend/apps/reports/urls.py
|
from django.conf.urls import patterns, url
from . import views
from . import api
urlpatterns = patterns(
"",
url(r"^api/exports/$", api.ExportListView.as_view(), name="exports"),
url(r"^api/exports/(?P<pk>[0-9]+)/$", api.ExportListView.as_view(), name="exports"),
url(r"^exports/download/(?P<file_name>[A-Za-z0-9-_\.]+)$", views.download_file, name="exports"),
url(
r"^mi-provider-allocation-extract/$",
views.mi_provider_allocation_extract,
name="mi_provider_allocation_extract",
),
url(r"^mi-case-extract/$", views.mi_case_extract, name="mi_case_extract"),
url(
r"^mi-case-view-audit-log-extract/$",
views.mi_case_view_audit_log_extract,
name="mi_case_view_audit_log_extract",
),
url(
r"^mi-complaint-view-audit-log-extract/$",
views.mi_complaint_view_audit_log_extract,
name="mi_complaint_view_audit_log_extract",
),
url(r"^mi-feedback-extract/$", views.mi_feedback_extract, name="mi_feedback_extract"),
url(r"^mi-duplicate-case-extract/$", views.mi_duplicate_case_extract, name="mi_duplicate_case_extract"),
url(r"^mi-contacts-per-case-extract/$", views.mi_contacts_extract, name="mi_contacts_extract"),
url(r"^mi-alternative-help-extract/$", views.mi_alternative_help_extract, name="mi_alternative_help_extract"),
url(r"^mi-survey-extract/$", views.mi_survey_extract, name="mi_survey_extract"),
url(r"^mi-cb1-extract/$", views.mi_cb1_extract, name="mi_cb1_extract"),
url(r"^mi-cb1-extract-agilisys/$", views.mi_cb1_extract_agilisys, name="mi_cb1_extract_agilisys"),
url(r"^mi-voice-extract/$", views.mi_voice_extract, name="mi_voice_extract"),
url(r"^mi-digital-case-type-extract/$", views.mi_digital_case_type_extract, name="mi_digital_case_type_extract"),
url(r"^mi-eod-extract/$", views.mi_eod_extract, name="mi_eod_extract"),
url(r"^mi-comlpaints/$", views.mi_complaints, name="mi_complaints"),
url(r"^mi-obiee-extract/$", views.mi_obiee_extract, name="mi_obiee_extract"),
url(r"^metrics-report/$", views.metrics_report, name="metrics_report"),
url(r"^all-knowledgebase-articles/$", views.all_knowledgebase_articles, name="all_knowledgebase_articles"),
)
|
adambirse/innovation-funding-service
|
ifs-data-layer/ifs-data-service/src/test/java/org/innovateuk/ifs/documentation/ApplicationSummaryDocs.java
|
package org.innovateuk.ifs.documentation;
import org.innovateuk.ifs.application.builder.ApplicationSummaryResourceBuilder;
import org.innovateuk.ifs.application.resource.FundingDecision;
import org.springframework.restdocs.payload.FieldDescriptor;
import java.math.BigDecimal;
import java.time.ZonedDateTime;
import static org.innovateuk.ifs.base.amend.BaseBuilderAmendFunctions.idBasedNames;
import static org.innovateuk.ifs.base.amend.BaseBuilderAmendFunctions.uniqueIds;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
public class ApplicationSummaryDocs {
public static final FieldDescriptor[] APPLICATION_SUMMARY_PAGE_RESOURCE_FIELDS = {
fieldWithPath("totalElements").description("Total size of the unpaged results set"),
fieldWithPath("totalPages").description("Total number of pages"),
fieldWithPath("number").description("Page number - zero indexed"),
fieldWithPath("size").description("Page size"),
fieldWithPath("content[].id").description("Application id"),
fieldWithPath("content[].name").description("Application name"),
fieldWithPath("content[].lead").description("Lead organisation"),
fieldWithPath("content[].leadApplicant").description("lead applicant"),
fieldWithPath("content[].status").description("Application status"),
fieldWithPath("content[].completedPercentage").description("Application completed percentage"),
fieldWithPath("content[].numberOfPartners").description("Number of partners on the application"),
fieldWithPath("content[].grantRequested").description("The grant requested on the application"),
fieldWithPath("content[].totalProjectCost").description("The total project cost of the application"),
fieldWithPath("content[].duration").description("Application duration in months"),
fieldWithPath("content[].fundingDecision").description("The funding decision for the application"),
fieldWithPath("content[].funded").description("Whether the application will be funded"),
fieldWithPath("content[].innovationArea").description("The innovation area of the application"),
fieldWithPath("content[].manageFundingEmailDate").description("The date of the last manage funding email sent"),
fieldWithPath("content[].ineligibleInformed").description("Whether the applicant has been informed the application is ineligible"),
fieldWithPath("content[].inAssessmentPanel").description("Whether the application has been chosen for assessment review panel")
};
public static final ApplicationSummaryResourceBuilder APPLICATION_SUMMARY_RESOURCE_BUILDER =
ApplicationSummaryResourceBuilder.newApplicationSummaryResource().
with(uniqueIds()).
with(idBasedNames("Application ")).
withFundingDecision(FundingDecision.values()).
withLead("A lead organisation").
withCompletedPercentage(20, 40, 60, 80, 100).
withDuration(2L, 4L, 6L, 8L, 10L).
withGrantRequested(new BigDecimal("500"), new BigDecimal("1000"), new BigDecimal("1500"), new BigDecimal("2000"), new BigDecimal("2500")).
withInnovationArea("Earth Observation", "Internet of Things", "Data", "Cyber Security", "User Experience").
withLeadApplicant("A lead user").
withManageFundingEmailDate(ZonedDateTime.now()).
withNumberOfPartners(1, 2, 3, 4, 5).
withIneligibleInformed(true, true, true, false, false);
}
|
Aryan-Madaan/CodeforcesCompetetions
|
CodeChef/Snackdown Qualifier/TestMatchSeries.cpp
|
<reponame>Aryan-Madaan/CodeforcesCompetetions<gh_stars>0
// Created by <NAME>.
//---------------------------------------------------------------------------------------------------
#include <bits/stdc++.h>
#include <stdio.h>
using namespace std;
#define Expresso std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define mod 1000000007
typedef long long ll;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<int> vi;
typedef long double ld;
typedef unsigned long long ull;
#define mp make_pair
#define ff first
#define ss second
#define pb(v) push_back(v)
#define INF 2e9
#define rep(i,n) for(int i =0;i<n;i++)
#define endl '\n'
const double eps = 1e-6, pi = acos(-1);
const char nl = '\n';
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
int randomize()
{
return (rand() % 1000);
}
//---------------------------------------------------------------------------------------------------
void solve()
{
int t=1;
cin >> t;
while(t--)
{
int ind=0,eng=0,draw=0,r=0;
for(int i =0;i<5;i++)
{
cin >> r;
if(r==0)
draw++;
else if(r==1)
ind++;
else
eng++;
}
if(ind==eng)
cout << "DRAW\n";
else if(ind>eng)
cout << "INDIA\n";
else
cout << "ENGLAND\n";
}
}
/*
*/
//---------------------------------------------------------------------------------------------------
int main() {
cout.precision(numeric_limits<double>::max_digits10);
cout << setprecision(15) << fixed;
Expresso
solve();
return 0;
}
|
lechium/tvOS142Headers
|
System/Library/PrivateFrameworks/AVConference.framework/Frameworks/ViceroyTrace.framework/SegmentStatsDelegate.h
|
/*
* This header is generated by classdump-dyld 1.5
* on Tuesday, November 10, 2020 at 10:16:08 PM Mountain Standard Time
* Operating System: Version 14.2 (Build 18K57)
* Image Source: /System/Library/PrivateFrameworks/AVConference.framework/Frameworks/ViceroyTrace.framework/ViceroyTrace
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>.
*/
@protocol SegmentStatsDelegate <NSObject>
@required
-(unsigned)significantVideoStallCount;
-(unsigned)audioErasureCount;
-(double)audioErasureTotalTime;
-(unsigned short)maxAudioErasureCount;
-(unsigned short)maxVideoStallCount;
-(double)averageJitterBufferDelay;
-(unsigned short)maxJBTargetSizeChanges;
-(unsigned short)minVideoFrameRate;
-(double)significantVideoStallTotalTime;
-(double)avgJBTargetSizeChanges;
-(double)timeWeightedNumberOfParticipants;
@end
|
nayotta/metathings
|
pkg/evaluatord/service/query_storage_by_device.go
|
package metathings_evaluatord_service
import (
"bytes"
"context"
"encoding/json"
"time"
"github.com/golang/protobuf/ptypes"
structpb "github.com/golang/protobuf/ptypes/struct"
log "github.com/sirupsen/logrus"
grpc_helper "github.com/nayotta/metathings/pkg/common/grpc"
policy_helper "github.com/nayotta/metathings/pkg/common/policy"
identityd_validator "github.com/nayotta/metathings/pkg/identityd2/validator"
"github.com/nayotta/metathings/proto/common/option/pagination"
deviced_pb "github.com/nayotta/metathings/proto/deviced"
pb "github.com/nayotta/metathings/proto/evaluatord"
dssdk "github.com/nayotta/metathings/sdk/data_storage"
)
func (srv *MetathingsEvaluatordService) ValidateQueryStorageByDevice(ctx context.Context, in interface{}) error {
return srv.validator.Validate(
identityd_validator.Providers{
func() (policy_helper.Validator, device_getter) {
req := in.(*pb.QueryStorageByDeviceRequest)
return req, req
},
},
identityd_validator.Invokers{},
)
}
func (srv *MetathingsEvaluatordService) AuthorizeQueryStorageByDevice(ctx context.Context, in interface{}) error {
return srv.authorizer.Authorize(ctx, in.(*pb.QueryStorageByDeviceRequest).GetDevice().GetId().GetValue(), "evaluatord:query_storage_by_device")
}
func (srv *MetathingsEvaluatordService) QueryStorageByDevice(ctx context.Context, req *pb.QueryStorageByDeviceRequest) (*pb.QueryStorageByDeviceResponse, error) {
var err error
dev := req.GetDevice()
dev_id := dev.GetId().GetValue()
src := req.GetSource()
src_id := src.GetId().GetValue()
src_typ := src.GetType().GetValue()
meas := req.GetMeasurement().GetValue()
logger := srv.get_logger().WithFields(log.Fields{
"device": dev_id,
"source_id": src_id,
"source_type": src_typ,
})
tags := map[string]string{
"$device_id": dev_id,
"$source_id": src_id,
"$source_type": src_typ,
}
var opts []dssdk.QueryOption
query_string := req.GetQueryString().GetValue()
opts = append(opts,
dssdk.QueryString(query_string),
dssdk.PageSize(srv.opt.Methods.QueryStorageByDevice.DefaultPageSize),
)
var range_from_ts time.Time
if range_from := req.GetRangeFrom(); range_from != nil {
range_from_ts, err = ptypes.Timestamp(range_from)
if err != nil {
logger.WithError(err).Errorf("range_from is invalid value")
return nil, srv.ParseError(err)
}
} else {
range_from_ts = time.Now().Add(srv.opt.Methods.QueryStorageByDevice.DefaultRangeFromDuration)
}
opts = append(opts, dssdk.RangeFrom(range_from_ts))
logger = logger.WithField("range_from", range_from_ts)
if range_to := req.GetRangeTo(); range_to != nil {
range_to_ts, err := ptypes.Timestamp(range_to)
if err != nil {
logger.WithError(err).Errorf("range_to is invalid value")
return nil, srv.ParseError(err)
}
opts = append(opts, dssdk.RangeTo(range_to_ts))
logger = logger.WithField("range_to", range_to_ts)
}
if pagination := req.GetPagination(); pagination != nil {
if page_size := pagination.GetPageSize(); page_size != nil {
page_size_i32 := page_size.GetValue()
opts = append(opts, dssdk.PageSize(page_size_i32))
logger = logger.WithField("page_size", page_size_i32)
}
if page_token := pagination.GetPageToken(); page_token != nil {
page_token_str := page_token.GetValue()
opts = append(opts, dssdk.PageToken(page_token_str))
logger = logger.WithField("page_token", page_token_str)
}
}
ret, err := srv.data_storage.Query(ctx, meas, tags, opts...)
if err != nil {
logger.WithError(err).Errorf("failed to query data in storage")
return nil, srv.ParseError(err)
}
var frms []*deviced_pb.Frame
for _, rec := range ret.Records() {
pbts, err := ptypes.TimestampProto(rec.Time())
if err != nil {
logger.WithError(err).Warningf("failed to parse record.time to protobuf timestamp")
continue
}
dat := rec.Data()
dat_buf, err := json.Marshal(dat)
if err != nil {
logger.WithError(err).Warningf("failed to parse record.data to json string")
continue
}
var dat_st structpb.Struct
err = grpc_helper.JSONPBUnmarshaler.Unmarshal(bytes.NewReader(dat_buf), &dat_st)
if err != nil {
logger.WithError(err).Warningf("failed to parse record.data json string to protobuf struct")
continue
}
frms = append(frms, &deviced_pb.Frame{
Ts: pbts,
Data: &dat_st,
})
}
res := &pb.QueryStorageByDeviceResponse{
Frames: frms,
Pagination: &pagination.PaginationOption{
NextPageToken: ret.NextPageToken(),
},
}
logger.Debugf("query storage by device")
return res, nil
}
|
codegrady/aliyun-openapi-java-sdk
|
aliyun-java-sdk-crm/src/main/java/com/aliyuncs/crm/model/v20150324/FindBizCategoryConfigResponse.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.aliyuncs.crm.model.v20150324;
import java.util.List;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.crm.transform.v20150324.FindBizCategoryConfigResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class FindBizCategoryConfigResponse extends AcsResponse {
private Boolean success;
private String resultCode;
private String resultMessage;
private List<BizCategory> data;
public Boolean getSuccess() {
return this.success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getResultCode() {
return this.resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
public String getResultMessage() {
return this.resultMessage;
}
public void setResultMessage(String resultMessage) {
this.resultMessage = resultMessage;
}
public List<BizCategory> getData() {
return this.data;
}
public void setData(List<BizCategory> data) {
this.data = data;
}
public static class BizCategory {
private String name;
private String code;
private Boolean isCheck;
private Boolean mainBiz;
private String other;
private List<BizSubCategory> subConfigs;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
public Boolean getIsCheck() {
return this.isCheck;
}
public void setIsCheck(Boolean isCheck) {
this.isCheck = isCheck;
}
public Boolean getMainBiz() {
return this.mainBiz;
}
public void setMainBiz(Boolean mainBiz) {
this.mainBiz = mainBiz;
}
public String getOther() {
return this.other;
}
public void setOther(String other) {
this.other = other;
}
public List<BizSubCategory> getSubConfigs() {
return this.subConfigs;
}
public void setSubConfigs(List<BizSubCategory> subConfigs) {
this.subConfigs = subConfigs;
}
public static class BizSubCategory {
private String name;
private String code;
private Boolean isCheck;
private Boolean mainBiz;
private String other;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
public Boolean getIsCheck() {
return this.isCheck;
}
public void setIsCheck(Boolean isCheck) {
this.isCheck = isCheck;
}
public Boolean getMainBiz() {
return this.mainBiz;
}
public void setMainBiz(Boolean mainBiz) {
this.mainBiz = mainBiz;
}
public String getOther() {
return this.other;
}
public void setOther(String other) {
this.other = other;
}
}
}
@Override
public FindBizCategoryConfigResponse getInstance(UnmarshallerContext context) {
return FindBizCategoryConfigResponseUnmarshaller.unmarshall(this, context);
}
}
|
MedleyJS/medley
|
test/extensions.test.js
|
<reponame>MedleyJS/medley
'use strict'
const {test} = require('tap')
const medley = require('..')
const request = require('./utils/request')
test('.extend() should be chainable', (t) => {
const app = medley()
.extend('a', 'aVal')
.extend('b', 'bVal')
t.equal(app.a, 'aVal')
t.equal(app.b, 'bVal')
t.end()
})
test('.extendRequest() should be chainable', (t) => {
medley()
.extendRequest('a', 'aVal')
.extendRequest('b', 'bVal')
t.end()
})
test('.extendResponse() should be chainable', (t) => {
medley()
.extendResponse('a', 'aVal')
.extendResponse('b', 'bVal')
t.end()
})
test('.extend() should throw if the property already exists', (t) => {
t.plan(1)
const app = medley()
app.extend('foo', 'value')
t.throws(
() => app.extend('foo', 'value'),
new Error("A 'foo' property already exists on the app")
)
})
test('.extendRequest() should throw if the property already exists', (t) => {
t.plan(1)
const app = medley()
app.extendRequest('foo', 'value')
t.throws(
() => app.extendRequest('foo', 'value'),
new Error("A 'foo' property already exists on the Request object")
)
})
test('.extendResponse() should throw if the property already exists', (t) => {
t.plan(1)
const app = medley()
app.extendResponse('foo', 'value')
t.throws(
() => app.extendResponse('foo', 'value'),
new Error("A 'foo' property already exists on the Response object")
)
})
test('.extendRequest() should not allow overwriting Medley values', (t) => {
const app = medley()
t.throws(
() => app.extendRequest('stream', null),
new Error("A 'stream' property already exists on the Request object")
)
t.throws(
() => app.extendRequest('headers', null),
new Error("A 'headers' property already exists on the Request object")
)
t.throws(
() => app.extendRequest('params', null),
new Error("A 'params' property already exists on the Request object")
)
t.throws(
() => app.extendRequest('body', null),
new Error("A 'body' property already exists on the Request object")
)
t.throws(
() => app.extendRequest('query', null),
new Error("A 'query' property already exists on the Request object")
)
t.end()
})
test('.extendResponse() should not allow overwriting Medley values', (t) => {
const app = medley()
t.throws(
() => app.extendResponse('stream', null),
new Error("A 'stream' property already exists on the Response object")
)
t.throws(
() => app.extendResponse('request', null),
new Error("A 'request' property already exists on the Response object")
)
t.throws(
() => app.extendResponse('sent', null),
new Error("A 'sent' property already exists on the Response object")
)
t.throws(
() => app.extendResponse('headers', null),
new Error("A 'headers' property already exists on the Response object")
)
t.throws(
() => app.extendResponse('state', null),
new Error("A 'state' property already exists on the Response object")
)
t.throws(
() => app.extendResponse('_route', null),
new Error("A '_route' property already exists on the Response object")
)
t.end()
})
test('app extensions are encapsulated in sub-apps', (t) => {
t.plan(2)
const app = medley()
const subApp = app.createSubApp()
subApp.extend('test', 'val')
t.equal(subApp.test, 'val')
t.equal(app.test, undefined)
})
test('cannot extend sub-app if parent app already has the property', (t) => {
t.plan(1)
const app = medley()
app.extend('foo', true)
const subApp = app.createSubApp()
t.throws(
() => subApp.extend('foo', 'other'),
new Error("A 'foo' property already exists on the app")
)
})
test('extendRequest inside a sub-app', (t) => {
t.plan(8)
const app = medley()
app.createSubApp()
.extendRequest('test', 'test')
.get('/sub', (req, res) => {
t.equal(req.test, 'test')
res.send()
})
app.get('/top', (req, res) => {
t.equal(req.test, 'test')
res.send()
})
request(app, '/sub', (err, res) => {
t.error(err)
t.equal(res.statusCode, 200)
t.equal(res.body.length, 0)
})
request(app, '/top', (err, res) => {
t.error(err)
t.equal(res.statusCode, 200)
t.equal(res.body.length, 0)
})
})
test('extendResponse inside a sub-app', (t) => {
t.plan(8)
const app = medley()
app.createSubApp()
.extendResponse('test', 'test')
.get('/sub', (req, res) => {
t.equal(res.test, 'test')
res.send()
})
app.get('/top', (req, res) => {
t.equal(res.test, 'test')
res.send()
})
request(app, '/sub', (err, res) => {
t.error(err)
t.equal(res.statusCode, 200)
t.equal(res.body.length, 0)
})
request(app, '/top', (err, res) => {
t.error(err)
t.equal(res.statusCode, 200)
t.equal(res.body.length, 0)
})
})
test('`this` inside an added function property refers to the extended object', (t) => {
t.plan(5)
const app = medley()
function returnThis() {
return this
}
app.extend('returnThis', returnThis)
app.extendRequest('returnThis', returnThis)
app.extendResponse('returnThis', returnThis)
t.equal(app.returnThis(), app)
const subApp = app.createSubApp()
t.equal(subApp.returnThis(), subApp)
app.get('/', (req, res) => {
t.equal(req.returnThis(), req)
t.equal(res.returnThis(), res)
res.send()
})
request(app, '/', (err) => {
t.error(err)
})
})
test('extensions should be app-independent', (t) => {
const app1 = medley()
const app2 = medley()
app1.extend('test', 'foo')
app2.extend('test', 'foo')
app1.extendRequest('test', 'foo')
app2.extendRequest('test', 'foo')
app1.extendResponse('test', 'foo')
app2.extendResponse('test', 'foo')
t.end()
})
|
hitlion/Rubymotion-Childern-app-for-iOS
|
app/models/story/story_object.rb
|
module Story
# A wrapper around a single object inside a screen.
# All vital properties can be accessed via attributes.
# Changes to the writeable attributes are traced and can be
# monitored using the {#changes} attribute.
class Object
include Story::SlotsMixin
include Story::AttributeValidationMixin
validation_scope :object
validation_scope :object_attribute
has_events :at_start, :at_end, :on_click, :on_swipe,
:start_moving, :end_moving, :new_position
attr_reader :id, :type, :processable, :resize, :moveable, :path,
:changes, :mask, :new_changes
attr_accessor :name, :content, :position, :size, :layer, :transparency
# Initialize a new Object instance
#
# @param [String] parent_path The document path of the objects parent.
def initialize( parent_path )
@id = -1
@name = 'undefined'
@changes = {}
@valid = false
@path = "#{parent_path}:object[-1]"
@new_changes = false
end
# Check if this object is valid.
# A freshly created object is always invalid an can only become
# valid once it's {#load} method was successfully called.
def valid?
@valid
end
# Load the object attributes from the +Hash+ in +description+.
#
# All attributes will be validated, type converted and
# - where appropriate and required - replaced with default values.
#
# @param [Hash] description A +Hash+ containing the initial values
# for this objects properties.
# @return [Boolean] true if the object was initialized successfully.
# false if the attributes where invalid or the object was already
# initialized by calling {#load} before.
def load( description )
return false if valid?
validate_attributes(description, :object) do |desc|
@id = desc[:object_id]
@name = desc[:object_name]
@type = desc[:object_type]
@processable = desc[:processable]
@content = desc[:object_content]
@mask = desc[:object_mask]
# now that @id is available update our @path
@path.gsub!(/:object\[[^\]]*\]$/, ":object[#{@id}]")
# +object_attribute+ is a +Hash+ in it's own and deserves
# it's own nested validation (also it has optionals..).
validate_attributes(desc[:object_attribute], :object_attribute) do |attribs|
@position = CGPoint.new(attribs[:position_x], attribs[:position_y])
@size = CGSize.new(attribs[:size_x], attribs[:size_y])
@layer = attribs[:layer]
@transparency = attribs[:transparency]
@resize = attribs[:resize]
@moveable = attribs[:moveable]
@size.width = (device.screen_height / device.screen_width) * @size.height if @size.width == -1
@size.height = (device.screen_width / device.screen_height) * @size.width if @size.height == -1
end
parse_events(desc[:object_event])
parse_slots(desc[:object_slot])
end
@valid = true if validation_errors.empty?
valid?
end
## mark: Change tracking
# @private
# Track modifications to the objects {#name} property
def name=( new_name )
@changes[:object_name] ||= { :value => nil, :original => @name }
@changes[:object_name][:value] = new_name
modified(true)
@name = new_name
end
# @private
# Track modifications to the objects {#content} property
def content=( new_content )
@changes[:object_content] ||= { :value => nil, :original => @content }
@changes[:object_content][:value] = new_content
modified(true)
@content = new_content
end
# @private
# Track modifications to the objects {#position} property
def position=( new_position )
@changes[:position_x] ||= { :value => nil, :original => @position.x }
@changes[:position_y] ||= { :value => nil, :original => @position.y }
@changes[:position_x][:value] = new_position.x
@changes[:position_y][:value] = new_position.y
modified(true)
@position = new_position
end
# @private
# Track modifications to the objects {#size} property
def size=( new_size )
@changes[:size_x] ||= { :value => nil, :original => @size.width }
@changes[:size_y] ||= { :value => nil, :original => @size.height }
@changes[:size_x][:value] = new_size.width
@changes[:size_y][:value] = new_size.height
modified(true)
@size = new_size
end
# @private
# Track modifications to the objects {#layer} property
def layer=( new_layer )
@changes[:layer] ||= { :value => nil, :original => @layer }
@changes[:layer][:value] = new_layer
modified(true)
@layer = new_layer
end
# @private
# Track modifications to the objects {#transparency} property
def transparency=( new_transparency )
@changes[:transparency] ||= { :value => nil, :original => @transparency }
@changes[:transparency][:value] = new_transparency
modified(true)
@transparency = new_transparency
end
# @private
# Fix the objects {#path} after copying it
def fix_path( parent_path )
@path = "#{parent_path}:object[-1]"
modified(true)
@path.gsub!(/:object\[[^\]]*\]$/, ":object[#{@id}]")
end
def modified(value)
@new_changes = value
end
end
end
|
tumblr/gocircuit
|
src/tumblr/scribe/thrift/scribe/ttypes.go
|
<gh_stars>10-100
// Copyright 2013 Tumblr, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/* Autogenerated by Thrift Compiler (0.9.0-dev)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
*/
package scribe
import (
"fmt"
"tumblr/encoding/thrift"
)
type ResultCode int
const (
OK ResultCode = 0
TRY_LATER ResultCode = 1
)
func (p ResultCode) String() string {
switch p {
case OK:
return "OK"
case TRY_LATER:
return "TRY_LATER"
}
return ""
}
func FromResultCodeString(s string) ResultCode {
switch s {
case "OK":
return OK
case "TRY_LATER":
return TRY_LATER
}
return ResultCode(-10000)
}
func (p ResultCode) Value() int {
return int(p)
}
func (p ResultCode) IsEnum() bool {
return true
}
/**
* Attributes:
* - Category
* - Message
*/
type LogEntry struct {
thrift.TStruct
Category string "category" // 1
Message string "message" // 2
}
func NewLogEntry() *LogEntry {
output := &LogEntry{
TStruct: thrift.NewTStruct("LogEntry", []thrift.TField{
thrift.NewTField("category", thrift.STRING, 1),
thrift.NewTField("message", thrift.STRING, 2),
}),
}
{
}
return output
}
func (p *LogEntry) Read(iprot thrift.TProtocol) (err thrift.TProtocolException) {
_, err = iprot.ReadStructBegin()
if err != nil {
return thrift.NewTProtocolExceptionReadStruct(p.ThriftName(), err)
}
for {
fieldName, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
if fieldId < 0 {
fieldId = int16(p.FieldIdFromFieldName(fieldName))
} else if fieldName == "" {
fieldName = p.FieldNameFromFieldId(int(fieldId))
}
if fieldTypeId == thrift.GENERIC {
fieldTypeId = p.FieldFromFieldId(int(fieldId)).TypeId()
}
if err != nil {
return thrift.NewTProtocolExceptionReadField(int(fieldId), fieldName, p.ThriftName(), err)
}
if fieldTypeId == thrift.STOP {
break
}
if fieldId == 1 || fieldName == "category" {
if fieldTypeId == thrift.STRING {
err = p.ReadField1(iprot)
if err != nil {
return thrift.NewTProtocolExceptionReadField(int(fieldId), fieldName, p.ThriftName(), err)
}
} else if fieldTypeId == thrift.VOID {
err = iprot.Skip(fieldTypeId)
if err != nil {
return thrift.NewTProtocolExceptionReadField(int(fieldId), fieldName, p.ThriftName(), err)
}
} else {
err = p.ReadField1(iprot)
if err != nil {
return thrift.NewTProtocolExceptionReadField(int(fieldId), fieldName, p.ThriftName(), err)
}
}
} else if fieldId == 2 || fieldName == "message" {
if fieldTypeId == thrift.STRING {
err = p.ReadField2(iprot)
if err != nil {
return thrift.NewTProtocolExceptionReadField(int(fieldId), fieldName, p.ThriftName(), err)
}
} else if fieldTypeId == thrift.VOID {
err = iprot.Skip(fieldTypeId)
if err != nil {
return thrift.NewTProtocolExceptionReadField(int(fieldId), fieldName, p.ThriftName(), err)
}
} else {
err = p.ReadField2(iprot)
if err != nil {
return thrift.NewTProtocolExceptionReadField(int(fieldId), fieldName, p.ThriftName(), err)
}
}
} else {
err = iprot.Skip(fieldTypeId)
if err != nil {
return thrift.NewTProtocolExceptionReadField(int(fieldId), fieldName, p.ThriftName(), err)
}
}
err = iprot.ReadFieldEnd()
if err != nil {
return thrift.NewTProtocolExceptionReadField(int(fieldId), fieldName, p.ThriftName(), err)
}
}
err = iprot.ReadStructEnd()
if err != nil {
return thrift.NewTProtocolExceptionReadStruct(p.ThriftName(), err)
}
return err
}
func (p *LogEntry) ReadField1(iprot thrift.TProtocol) (err thrift.TProtocolException) {
v0, err1 := iprot.ReadString()
if err1 != nil {
return thrift.NewTProtocolExceptionReadField(1, "category", p.ThriftName(), err1)
}
p.Category = v0
return err
}
func (p *LogEntry) ReadFieldCategory(iprot thrift.TProtocol) thrift.TProtocolException {
return p.ReadField1(iprot)
}
func (p *LogEntry) ReadField2(iprot thrift.TProtocol) (err thrift.TProtocolException) {
v2, err3 := iprot.ReadString()
if err3 != nil {
return thrift.NewTProtocolExceptionReadField(2, "message", p.ThriftName(), err3)
}
p.Message = v2
return err
}
func (p *LogEntry) ReadFieldMessage(iprot thrift.TProtocol) thrift.TProtocolException {
return p.ReadField2(iprot)
}
func (p *LogEntry) Write(oprot thrift.TProtocol) (err thrift.TProtocolException) {
err = oprot.WriteStructBegin("LogEntry")
if err != nil {
return thrift.NewTProtocolExceptionWriteStruct(p.ThriftName(), err)
}
err = p.WriteField1(oprot)
if err != nil {
return err
}
err = p.WriteField2(oprot)
if err != nil {
return err
}
err = oprot.WriteFieldStop()
if err != nil {
return thrift.NewTProtocolExceptionWriteField(-1, "STOP", p.ThriftName(), err)
}
err = oprot.WriteStructEnd()
if err != nil {
return thrift.NewTProtocolExceptionWriteStruct(p.ThriftName(), err)
}
return err
}
func (p *LogEntry) WriteField1(oprot thrift.TProtocol) (err thrift.TProtocolException) {
err = oprot.WriteFieldBegin("category", thrift.STRING, 1)
if err != nil {
return thrift.NewTProtocolExceptionWriteField(1, "category", p.ThriftName(), err)
}
err = oprot.WriteString(string(p.Category))
if err != nil {
return thrift.NewTProtocolExceptionWriteField(1, "category", p.ThriftName(), err)
}
err = oprot.WriteFieldEnd()
if err != nil {
return thrift.NewTProtocolExceptionWriteField(1, "category", p.ThriftName(), err)
}
return err
}
func (p *LogEntry) WriteFieldCategory(oprot thrift.TProtocol) thrift.TProtocolException {
return p.WriteField1(oprot)
}
func (p *LogEntry) WriteField2(oprot thrift.TProtocol) (err thrift.TProtocolException) {
err = oprot.WriteFieldBegin("message", thrift.STRING, 2)
if err != nil {
return thrift.NewTProtocolExceptionWriteField(2, "message", p.ThriftName(), err)
}
err = oprot.WriteString(string(p.Message))
if err != nil {
return thrift.NewTProtocolExceptionWriteField(2, "message", p.ThriftName(), err)
}
err = oprot.WriteFieldEnd()
if err != nil {
return thrift.NewTProtocolExceptionWriteField(2, "message", p.ThriftName(), err)
}
return err
}
func (p *LogEntry) WriteFieldMessage(oprot thrift.TProtocol) thrift.TProtocolException {
return p.WriteField2(oprot)
}
func (p *LogEntry) TStructName() string {
return "LogEntry"
}
func (p *LogEntry) ThriftName() string {
return "LogEntry"
}
func (p *LogEntry) String() string {
if p == nil {
return "<nil>"
}
return fmt.Sprintf("LogEntry(%+v)", *p)
}
func (p *LogEntry) CompareTo(other interface{}) (int, bool) {
if other == nil {
return 1, true
}
data, ok := other.(*LogEntry)
if !ok {
return 0, false
}
return thrift.TType(thrift.STRUCT).Compare(p, data)
}
func (p *LogEntry) AttributeByFieldId(id int) interface{} {
switch id {
default:
return nil
case 1:
return p.Category
case 2:
return p.Message
}
return nil
}
func (p *LogEntry) TStructFields() thrift.TFieldContainer {
return thrift.NewTFieldContainer([]thrift.TField{
thrift.NewTField("category", thrift.STRING, 1),
thrift.NewTField("message", thrift.STRING, 2),
})
}
func init() {
}
|
illuminatixs-newbms/Lidium
|
scripts/portal/jail_out.js
|
/**
* @author: Ronan
* @event: Jail
*/
function enter(pi) {
var jailedTime = pi.getJailTimeLeft();
if(jailedTime <= 0) {
pi.playPortalSound(); pi.warp(300000010,"in01");
return true;
}
else {
var seconds = Math.floor(jailedTime / 1000) % 60 ;
var minutes = (Math.floor(jailedTime / (1000*60)) % 60);
var hours = (Math.floor(jailedTime / (1000*60*60)) % 24);
pi.playerMessage(5, "You have been caught in bad behaviour by the Maple POLICE. You've got to stay here for " + hours + " hours " + minutes + " minutes " + seconds + " seconds yet.");
return false;
}
}
|
jwoo1601/Java-Minecraft-Mods
|
[Universal] 3Kids Sudden Surivival/src/main/java/jwk/suddensurvival/block/BlockFenceImpl.java
|
<gh_stars>0
package jwk.suddensurvival.block;
import static net.minecraftforge.common.util.ForgeDirection.UP;
import net.minecraft.block.BlockFence;
import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks;
import net.minecraft.world.World;
public class BlockFenceImpl extends BlockFence {
public BlockFenceImpl(String blockName, String textureName, Material material) {
super(textureName, material);
this.setBlockName(blockName);
}
public boolean canPlaceTorchOnTop(World world, int x, int y, int z) {
return true;
}
public String getBlockName() { return this.getUnlocalizedName().replace("tile.", ""); }
}
|
hu19891110/keke
|
public/themes/default/assets/js/cashout.js
|
<gh_stars>0
/**
* Created by kuke on 2016/5/4.
*/
$(function(){
var demo=$(".registerform").Validform({
btnSubmit:"#btn_sub",
tiptype:3,
label:".label",
showAllError:true,
datatype:{
"number":/^\d+(\.\d{1,2})?$/,
},
});
$('.lbl-bank').on('click',function(){
$('.lbl-bank').removeClass('lbl-active');
$(this).addClass('lbl-active');
});
$('.g-recharge .cashier-alert').click(function(){
$('.cashier-alert-cont').toggle(500);
})
})
|
tvasset/momentum-ui
|
charts/src/lib/area/example/index.js
|
import MomentumCharts from '../../index.js';
const example = () => {
const colorSets = MomentumCharts.colors('10Colors');
const colors = colorSets.scheme(10);
const scaleX = MomentumCharts.scale('scaleLinear', {
domain: [0, 4],
range: [100, 700]
}).Scale;
const scaleY = MomentumCharts.scale('scaleLinear', {
domain: [0, 80],
range: [350, 50]
}).Scale;
let areaGenerator = {
x: function (d, i) {
return scaleX(i);
},
y1: function (d) {
return scaleY(d.y1);
},
y0: function (d) {
return scaleY(d.y0 - 1);
}
};
let shapeData = [
[20, 35, 55, 65, 50],
[15, 30, 35, 55, 45],
[10, 20, 25, 45, 40],
[5, 10, 15, 25, 30],
[1, 1, 1, 1, 1]
];
let boardData = {
shape: {},
legends: ['Cisco Webex Teams', 'Cisco Webex Meetings', 'Cisco Jabber', 'Device']
};
for (let j = 1; j < 5; j++) {
boardData.shape['d' + j] = [];
for (let _j = 0; _j < 5; _j++) {
boardData.shape['d' + j].push({
y0: shapeData[j - 1][_j],
y1: shapeData[j][_j]
});
}
}
let board = MomentumCharts.board('#app', {
attr: {
width: '800',
height: '400',
viewBox: "0 0 800 400"
}
});
board.data(boardData);
board.legends('legends', {
generator: {
x: 100,
y: 370,
type: 'horizontal',
iconType: 'dot',
text: function (d) {
return d;
},
iconColor: function (d, i) {
return colors[+i + 5].toString();
}
}
});
board.axis('x', {
generator: {
scale: scaleX,
y: scaleY.range()[0],
tickFormat: function () {
return '';
},
tickSize: -10
},
modify: {
style: {
stroke: '#A3A3A3'
}
}
});
board.axis('y', {
generator: {
scale: scaleY,
x: scaleX.range()[0],
tickSize: scaleX.range()[0] - scaleX.range()[1]
},
modify: {
style: {
stroke: '#A3A3A3'
}
}
});
for (var i = 1, l = 5; i < l; i++) {
board.area('shape/d' + i, {
generator: areaGenerator,
modify: {
style: {
fill: colors[(+i + 5)].toString(),
'stroke-width': 2,
opacity: 0.85
}
}
});
}
board.render();
};
export default example;
|
JosephUz/fish-market
|
client/src/views/cards/ConfirmCard.js
|
import React, { Component } from 'react';
import { userMapper } from '../../store/mappers';
class ConfirmCard extends Component {
constructor(props) {
super(props);
this.state = {
confirmed: false
};
this.callBack = this.callBack.bind(this);
}
componentWillMount() {
this.props.confirmUser(this.callBack);
}
callBack() {
this.setState({
confirmed: true
});
}
render() {
const text = this.state.confirmed
? 'Your account has been confirmed.'
: 'Waiting...';
return (
<div className="container mt--8 pb-5">
<div className="row justify-content-center">
<div className="col-lg-5 col-md-7">
<div className="card bg-secondary shadow border-0">
<div className="card-body px-lg-5 py-lg-5">
<div className="text-center text-muted">
<small>{text}</small>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default userMapper(ConfirmCard);
|
ess-dmsc/nicos
|
nicos_mlz/labs/puma/multidet/setups/cad.py
|
<gh_stars>1-10
description = 'Combined multianalyzer axis setup'
group = 'lowlevel'
# includes = ['analyzer']
devices = dict(
st_att = device('nicos.devices.generic.VirtualMotor',
unit = 'deg',
abslimits = (-117, 117),
speed = 0.5,
lowlevel = True,
),
# cad = device('nicos_mlz.puma.devices.PumaCoupledAxis',
# description = 'cad - combined axis for multianalyzer',
# tt = 'att_cad',
# th = 'ath',
# fmtstr = '%.3f',
# unit = 'deg',
# precision = .1,
# ),
att_cad = device('nicos.devices.generic.Axis',
description = 'Scattering angle two-theta of analyser',
motor = 'st_att',
precision = 0.01,
offset = 90.,
# offset = 0.,
jitter = 0.2,
dragerror = 1,
maxtries = 30,
# lowlevel = True,
),
)
startupcode = '''
# att.userlimits = (-117, 117)
# ath.userlimits = (0, 60)
'''
|
gpe-tech/ranger-clubhouse-web
|
app/constants/bmid.js
|
import {
IN_PREP, DO_NOT_PRINT,
READY_TO_PRINT, READY_TO_REPRINT_CHANGE, READY_TO_REPRINT_LOST,
ISSUES, SUBMITTED,
MEALS_ALL,
MEALS_PRE, MEALS_PRE_PLUS_EVENT, MEALS_PRE_PLUS_POST,
MEALS_EVENT, MEALS_EVENT_PLUS_POST,
MEALS_POST
} from 'clubhouse/models/bmid';
export const BmidStatusLabels = {
[IN_PREP]: 'Prep',
[DO_NOT_PRINT]: 'Do Not Print',
[READY_TO_PRINT]: 'Ready To Print',
[READY_TO_REPRINT_LOST]: 'Ready To Reprint (Lost)',
[READY_TO_REPRINT_CHANGE]: 'Ready To Reprint (Changed)',
[ISSUES]: 'Issues',
[SUBMITTED]: 'Submitted',
};
export const BmidStatusOptions = [
['Prep', IN_PREP],
['Do Not Print', DO_NOT_PRINT],
['Ready To Print', READY_TO_PRINT],
['Ready To Reprint (Lost)', READY_TO_REPRINT_LOST],
['Ready To Reprint (Changed)', READY_TO_REPRINT_CHANGE],
['Issues', ISSUES],
['Submitted', SUBMITTED]
];
export const MealLabels = {
[MEALS_PRE]: 'Pre',
[MEALS_POST]: 'Post',
[MEALS_EVENT]: 'Event',
[MEALS_ALL]: 'All',
[MEALS_PRE_PLUS_POST]: 'Pre+Post',
[MEALS_PRE_PLUS_EVENT]: 'Pre+Event',
[MEALS_EVENT_PLUS_POST]: 'Event+Post',
};
export const MealOptions = [
['None', ''],
['Pre', MEALS_PRE],
['Post', MEALS_POST],
['Event', MEALS_EVENT],
['All', MEALS_ALL],
['Pre+Post', MEALS_PRE_PLUS_POST],
['Pre+Event', MEALS_PRE_PLUS_EVENT],
['Event+Post', MEALS_EVENT_PLUS_POST]
];
export const ShowerOptions = [
['No', false],
['Yes', true],
];
|
dspsforms/dspsAdvisingFlow
|
dspsmisc-backend/models/aap2-form-model.js
|
<gh_stars>0
const mongoose = require('mongoose');
const commonFormSchema = require('./common-form-schema');
module.exports = mongoose.model('aap2', commonFormSchema);
|
Bullgator351/throneteki
|
server/game/cards/10-SoD/SeptonMeribald.js
|
const DrawCard = require('../../drawcard');
class SeptonMeribald extends DrawCard {
setupCardAbilities(ability) {
this.action({
title: 'Stand up to 3 characters',
cost: ability.costs.kneelSelf(),
target: {
mode: 'upTo',
numCards: 3,
cardCondition: card => card.location === 'play area' && card.getType() === 'character' &&
card.getPrintedStrength() <= 1 && card.kneeled,
gameAction: 'stand'
},
message: '{player} kneels {source} to stand {target}',
handler: context => {
for(let card of context.target) {
card.controller.standCard(card);
}
},
limit: ability.limit.perRound(1)
});
}
}
SeptonMeribald.code = '10040';
module.exports = SeptonMeribald;
|
josenorberto/concerto-platform
|
src/Concerto/PanelBundle/Resources/public/angularjs/app/concerto_panel/js/controllers/textarea_controller.js
|
<reponame>josenorberto/concerto-platform<filename>src/Concerto/PanelBundle/Resources/public/angularjs/app/concerto_panel/js/controllers/textarea_controller.js
function TextareaController($scope, $uibModalInstance, value, readonly, title, tooltip) {
$scope.value = value;
$scope.readonly = readonly;
$scope.title = title;
$scope.tooltip = tooltip;
$scope.close = function () {
$uibModalInstance.close($scope.value);
};
$scope.cancel = function () {
$uibModalInstance.dismiss(0);
};
}
|
prydin/opentelemetry-auto-instr-java
|
java-agent/instrumentation/java-concurrent/src/main/java/io/opentelemetry/auto/instrumentation/java/concurrent/AsyncPropagatingDisableInstrumentation.java
|
package io.opentelemetry.auto.instrumentation.java.concurrent;
import static io.opentelemetry.auto.instrumentation.api.AgentTracer.activateSpan;
import static io.opentelemetry.auto.instrumentation.api.AgentTracer.activeSpan;
import static io.opentelemetry.auto.instrumentation.api.AgentTracer.noopSpan;
import static io.opentelemetry.auto.tooling.ByteBuddyElementMatchers.safeHasSuperType;
import static java.util.Collections.singletonMap;
import static net.bytebuddy.matcher.ElementMatchers.named;
import com.google.auto.service.AutoService;
import com.google.common.collect.ImmutableMap;
import io.opentelemetry.auto.instrumentation.api.AgentScope;
import io.opentelemetry.auto.instrumentation.api.AgentSpan;
import io.opentelemetry.auto.tooling.Instrumenter;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;
import net.bytebuddy.matcher.ElementMatchers;
/**
* Sometimes classes do lazy initialization for scheduling of tasks. If this is done during a trace
* it can cause the trace to never be reported. Add matchers below to disable async propagation
* during this period.
*/
@Slf4j
@AutoService(Instrumenter.class)
public final class AsyncPropagatingDisableInstrumentation implements Instrumenter {
private static final Map<
ElementMatcher<? super TypeDescription>, ElementMatcher<? super MethodDescription>>
CLASS_AND_METHODS =
new ImmutableMap.Builder<
ElementMatcher<? super TypeDescription>,
ElementMatcher<? super MethodDescription>>()
.put(safeHasSuperType(named("rx.Scheduler$Worker")), named("schedulePeriodically"))
.build();
@Override
public AgentBuilder instrument(AgentBuilder agentBuilder) {
for (final Map.Entry<
ElementMatcher<? super TypeDescription>, ElementMatcher<? super MethodDescription>>
entry : CLASS_AND_METHODS.entrySet()) {
agentBuilder =
new DisableAsyncInstrumentation(entry.getKey(), entry.getValue())
.instrument(agentBuilder);
}
return agentBuilder;
}
// Not Using AutoService to hook up this instrumentation
public static class DisableAsyncInstrumentation extends Default {
private final ElementMatcher<? super TypeDescription> typeMatcher;
private final ElementMatcher<? super MethodDescription> methodMatcher;
/** No-arg constructor only used by muzzle and tests. */
public DisableAsyncInstrumentation() {
this(ElementMatchers.<TypeDescription>none(), ElementMatchers.<MethodDescription>none());
}
public DisableAsyncInstrumentation(
final ElementMatcher<? super TypeDescription> typeMatcher,
final ElementMatcher<? super MethodDescription> methodMatcher) {
super(AbstractExecutorInstrumentation.EXEC_NAME);
this.typeMatcher = typeMatcher;
this.methodMatcher = methodMatcher;
}
@Override
public ElementMatcher<? super TypeDescription> typeMatcher() {
return typeMatcher;
}
@Override
public Map<? extends ElementMatcher<? super MethodDescription>, String> transformers() {
return singletonMap(
methodMatcher,
AsyncPropagatingDisableInstrumentation.class.getName() + "$DisableAsyncAdvice");
}
}
public static class DisableAsyncAdvice {
@Advice.OnMethodEnter(suppress = Throwable.class)
public static AgentScope enter() {
final AgentSpan span = activeSpan();
if (span != null) {
return activateSpan(noopSpan(), false);
}
return null;
}
@Advice.OnMethodExit(suppress = Throwable.class)
public static void exit(@Advice.Enter final AgentScope scope) {
if (scope != null) {
scope.close();
}
}
}
}
|
UCLA-SEAL/JShrink
|
code/experiment_resources/ohloh_projects/maven-config-processor-plugin/src/main/java/com/google/code/configprocessor/processing/properties/AbstractPropertiesActionProcessingAdvisor.java
|
/*
* Copyright (C) 2009 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.code.configprocessor.processing.properties;
import com.google.code.configprocessor.expression.*;
import com.google.code.configprocessor.processing.properties.model.*;
public abstract class AbstractPropertiesActionProcessingAdvisor implements PropertiesActionProcessingAdvisor {
private ExpressionResolver expressionResolver;
public AbstractPropertiesActionProcessingAdvisor(ExpressionResolver expressionResolver) {
this.expressionResolver = expressionResolver;
}
/**
* Default implementation to indicate do nothing.
*/
public PropertiesFileItemAdvice onStartProcessing() {
return new PropertiesFileItemAdvice(PropertiesFileItemAdviceType.DO_NOTHING, null);
}
/**
* Default implementation to indicate do nothing.
*/
public PropertiesFileItemAdvice process(PropertiesFileItem item) {
return new PropertiesFileItemAdvice(PropertiesFileItemAdviceType.DO_NOTHING, null);
}
/**
* Default implementation to indicate do nothing.
*/
public PropertiesFileItemAdvice onEndProcessing() {
return new PropertiesFileItemAdvice(PropertiesFileItemAdviceType.DO_NOTHING, null);
}
protected PropertyMapping createPropertyMapping(String name, String value) {
return new PropertyMapping(name, resolve(value));
}
protected String resolve(String value) {
return expressionResolver.resolve(value, true);
}
}
|
LambdaInnovation/LambdaLib
|
src/main/java/cn/lambdalib/util/mc/SideHelper.java
|
/**
* Copyright (c) Lambda Innovation, 2013-2016
* This file is part of LambdaLib modding library.
* https://github.com/LambdaInnovation/LambdaLib
* Licensed under MIT, see project root for more information.
*/
package cn.lambdalib.util.mc;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraftforge.common.DimensionManager;
import java.util.List;
public class SideHelper {
private static ThreadLocal<SideHelper> threadProxy = new ThreadLocal<SideHelper>() {
@Override protected SideHelper initialValue() {
Side s = FMLCommonHandler.instance().getEffectiveSide();
if (s.isClient()) {
return new SideHelper(getClientProxy());
} else {
return new SideHelper(new ServerProxy());
}
}
@SideOnly(Side.CLIENT)
private ServerProxy getClientProxy() {
return new ClientProxy();
}
};
private final ServerProxy proxy;
private SideHelper(ServerProxy proxy) {
this.proxy = proxy;
}
public static World getWorld(int dimension) {
return threadProxy.get().proxy.getWorld(dimension);
}
public static Container getPlayerContainer(EntityPlayer player, int windowId) {
return threadProxy.get().proxy.getPlayerContainer(player, windowId);
}
public static Side getRuntimeSide() {
return FMLCommonHandler.instance().getEffectiveSide();
}
public static EntityPlayer getThePlayer() {
return threadProxy.get().proxy.getThePlayer();
}
public static EntityPlayer getPlayerOnServer(String name) {
return threadProxy.get().proxy.getPlayerOnServer(name);
}
public static EntityPlayer[] getPlayerList() {
return threadProxy.get().proxy.getPlayerList();
}
public static boolean isClient() {
return getRuntimeSide().isClient();
}
private static class ServerProxy {
public World getWorld(int dimension) {
return DimensionManager.getWorld(dimension);
}
public Container getPlayerContainer(EntityPlayer player, int windowId) {
Container ret = player.openContainer;
if (ret.windowId == windowId) {
return ret;
}
return null;
}
public EntityPlayer getThePlayer() {
return null;
}
public EntityPlayer getPlayerOnServer(String name) {
return MinecraftServer.getServer().getConfigurationManager().func_152612_a(name);
}
@SuppressWarnings("unchecked")
public EntityPlayer[] getPlayerList() {
List<? extends EntityPlayer> list = (List<? extends EntityPlayer>) MinecraftServer.getServer()
.getConfigurationManager().playerEntityList;
return list.toArray(new EntityPlayer[list.size()]);
}
}
@SideOnly(Side.CLIENT)
private static class ClientProxy extends ServerProxy {
@Override
public World getWorld(int dimension) {
World theWorld = Minecraft.getMinecraft().theWorld;
if (theWorld != null && theWorld.provider.dimensionId == dimension) {
return theWorld;
} else {
return null;
}
}
@Override
public Container getPlayerContainer(EntityPlayer player, int windowId) {
Container ret = Minecraft.getMinecraft().thePlayer.openContainer;
if (ret.windowId == windowId) {
return ret;
} else {
return null;
}
}
@Override
public EntityPlayer getThePlayer() {
return Minecraft.getMinecraft().thePlayer;
}
@Override
public EntityPlayer getPlayerOnServer(String name) {
return null;
}
@Override
public EntityPlayer[] getPlayerList() {
return new EntityPlayer[] {};
}
}
}
|
OlenaStoliarova/java-training
|
ExceptionsFromGolovachCourse/src/pessimistic_throw/SeveralExceptions.java
|
<gh_stars>0
package pessimistic_throw;
//Рассмотрим ситуацию с кодом, который может бросать проверяемые исключения разных типов.
//Далее учитывайте, что EOFException и FileNotFoundException — потомки IOException.
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
public class SeveralExceptions {
//Можно и вот так: EOFException и FileNotFoundException «обобщаем до» IOException,
// а InterruptedException «пропускаем нетронутым» (InterruptedException — НЕ потомок IOException)
public static void main(String[] args) throws IOException, InterruptedException {
f0();
f1();
f2();
}
public static void f0() throws EOFException {}
public static void f1() throws FileNotFoundException {}
public static void f2() throws InterruptedException {}
// CORRECT
/*
// пугаем ПРЕДКОМ исключений
public static void main(String[] args) throws IOException {
f0();
f1();
}
public static void f0() throws EOFException {}
public static void f1() throws FileNotFoundException {}
// CORRECT
*/
/*
//А можем «испугать» сильнее (предком обоих исключений)
// пугаем ПРЕДКОМ исключений
public static void main(String[] args) throws IOException {
if (System.currentTimeMillis() % 2 == 0) {
throw new EOFException();
} else {
throw new FileNotFoundException();
}
}
// CORRECT
*/
/*
// пугаем ОБОИМИ исключениями
public static void main(String[] args) throws EOFException, FileNotFoundException {
f0();
f1();
}
public static void f0() throws EOFException {}
public static void f1() throws FileNotFoundException {}
// CORRECT
*/
/*
//Мы можем точно указать, что выбрасываем
// пугаем ОБОИМИ исключениями
public static void main(String[] args) throws EOFException, FileNotFoundException {
if (System.currentTimeMillis() % 2 == 0) {
throw new EOFException();
} else {
throw new FileNotFoundException();
}
}
// CORRECT
*/
}
|
noobatl/gtProject2
|
routes/api-user.js
|
const db = require("../models");
module.exports = function (app) {
app.get("/api/user", function (req, res) {
db.User.findAll({}).then(function (dbUser) {
res.json(dbUser);
});
});
app.get("/api/user/:id", function (req, res) {
db.User.findOne({
where: {
id: req.params.id,
},
}).then(function (dbUser) {
res.json(dbUser);
});
});
app.post("/api/user", function (req, res) {
db.User.create(req.body).then(function (dbUser) {
res.json(dbUser);
});
});
app.delete("/api/user/:id", function (req, res) {
db.User.destroy({
where: {
id: req.params.id,
},
}).then(function (dbUser) {
res.json(dbUser);
});
});
app.put("/api/user", function (req, res) {
db.User.update(req.body, {
where: {
id: req.body.id,
},
}).then(function (dbUser) {
res.json(dbUser);
});
});
};
|
cyberflamingo/launch-school-rb101
|
exercises/RB101_small_problems/medium_1/03_rotation_part_3.rb
|
def rotate_array(list)
rotated_list = list.dup
rotated_list << rotated_list.shift
rotated_list
end
def rotate_rightmost_digits(number, n)
leftmost_digits = number.to_s[0...-n]
rightmost_digits = rotate_array(number.to_s[-n..-1].chars)
(leftmost_digits + rightmost_digits.join).to_i
end
def max_rotation(number)
(number.to_s.size).downto(2) do |index|
number = rotate_rightmost_digits(number, index)
end
number
end
p max_rotation(735291) == 321579
p max_rotation(3) == 3
p max_rotation(35) == 53
p max_rotation(105) == 15 # the leading zero gets dropped
p max_rotation(8_703_529_146) == 7_321_609_845
# Further Exploration
p max_rotation(87_003_529_146) == 70_594_831_062 # No error with the two zeros
|
cattlepotato/gatk_ca
|
src/test/java/org/broadinstitute/hellbender/tools/exome/sexgenotyper/ContigGermlinePloidyAnnotationTableReaderUnitTest.java
|
<filename>src/test/java/org/broadinstitute/hellbender/tools/exome/sexgenotyper/ContigGermlinePloidyAnnotationTableReaderUnitTest.java
package org.broadinstitute.hellbender.tools.exome.sexgenotyper;
import org.broadinstitute.hellbender.exceptions.UserException;
import org.broadinstitute.hellbender.utils.test.BaseTest;
import org.testng.annotations.Test;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/**
* Unit tests for {@link ContigGermlinePloidyAnnotationTableReader}.
*
* @author <NAME> <<EMAIL>>
*/
public class ContigGermlinePloidyAnnotationTableReaderUnitTest extends BaseTest {
private static final String TEST_SUB_DIR = publicTestDir + "org/broadinstitute/hellbender/tools/exome/sexgenotyper/";
private static final File BAD_CONTIG_PLOIDY_ANNOTS_FILE_1 = new File(TEST_SUB_DIR, "contig_annots_bad_autosomal_annot.tsv");
private static final File BAD_CONTIG_PLOIDY_ANNOTS_FILE_2 = new File(TEST_SUB_DIR, "contig_annots_bad_class.tsv");
private static final File BAD_CONTIG_PLOIDY_ANNOTS_FILE_3 = new File(TEST_SUB_DIR, "contig_annots_bad_missing_some_annots.tsv");
/* autosomal contigs can not have different plodies on different classes */
@Test(expectedExceptions = UserException.BadInput.class)
public void testBadAutosomalContigPloidyValues() {
try {
final ContigGermlinePloidyAnnotationTableReader reader = new ContigGermlinePloidyAnnotationTableReader(
new FileReader(BAD_CONTIG_PLOIDY_ANNOTS_FILE_1));
reader.stream().count();
} catch (IOException ex) {
throw new UserException.CouldNotReadInputFile("Could not read test resource file");
}
}
/* only AUTOSOMAL or ALLOSOMAL is acceptable */
@Test(expectedExceptions = UserException.BadInput.class)
public void testBadContigClass() {
try {
final ContigGermlinePloidyAnnotationTableReader reader = new ContigGermlinePloidyAnnotationTableReader(
new FileReader(BAD_CONTIG_PLOIDY_ANNOTS_FILE_2));
reader.stream().count();
} catch (IOException ex) {
throw new UserException.CouldNotReadInputFile("Could not read test resource file");
}
}
/* all lines in the table must have all values for the ploidy classes defined in the header */
@Test(expectedExceptions = UserException.BadInput.class)
public void testBadMissingSomeAnnotations() {
try {
final ContigGermlinePloidyAnnotationTableReader reader = new ContigGermlinePloidyAnnotationTableReader(
new FileReader(BAD_CONTIG_PLOIDY_ANNOTS_FILE_3));
reader.stream().count();
} catch (IOException ex) {
throw new UserException.CouldNotReadInputFile("Could not read test resource file");
}
}
}
|
bdshadow/kubernetes-client-android
|
kubernetes-model/vendor/github.com/openshift/origin/pkg/route/generator/generate_test.go
|
<filename>kubernetes-model/vendor/github.com/openshift/origin/pkg/route/generator/generate_test.go<gh_stars>0
/**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package generator
import (
"reflect"
"testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
routeapi "github.com/openshift/origin/pkg/route/apis/route"
)
func TestGenerateRoute(t *testing.T) {
generator := RouteGenerator{}
tests := []struct {
params map[string]interface{}
expected routeapi.Route
}{
{
params: map[string]interface{}{
"labels": "foo=bar",
"name": "test",
"default-name": "someservice",
"port": "80",
"ports": "80,443",
"target-port": "svcportname",
"hostname": "www.example.com",
},
expected: routeapi.Route{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
Labels: map[string]string{
"foo": "bar",
},
},
Spec: routeapi.RouteSpec{
Host: "www.example.com",
To: routeapi.RouteTargetReference{
Name: "someservice",
},
Port: &routeapi.RoutePort{
TargetPort: intstr.IntOrString{
Type: intstr.Int,
IntVal: 80,
},
},
},
},
},
{
params: map[string]interface{}{
"labels": "foo=bar",
"name": "test",
"default-name": "someservice",
"port": "web",
"ports": "80,443",
"hostname": "www.example.com",
},
expected: routeapi.Route{
ObjectMeta: metav1.ObjectMeta{
Name: "test",
Labels: map[string]string{
"foo": "bar",
},
},
Spec: routeapi.RouteSpec{
Host: "www.example.com",
Port: &routeapi.RoutePort{
TargetPort: intstr.IntOrString{
Type: intstr.String,
StrVal: "web",
},
},
To: routeapi.RouteTargetReference{
Name: "someservice",
},
},
},
},
}
for _, test := range tests {
obj, err := generator.Generate(test.params)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !reflect.DeepEqual(obj, &test.expected) {
t.Errorf("expected:\n%#v\ngot\n%#v\n", &test.expected, obj)
}
}
}
|
fscm/multicurrency
|
tests/test_dollar.py
|
<gh_stars>1-10
# -*- coding: UTF-8 -*-
#
# copyright: 2020-2022, <NAME>
# author: <NAME> <http://github.com/fscm>
# license: SPDX-License-Identifier: MIT
"""Tests for the Dollar currency representation(s)."""
from decimal import Context
from pytest import raises
from multicurrency import Currency
from multicurrency import (
CurrencyMismatchException,
CurrencyTypeException)
CONTEXT = Context(prec=28, rounding='ROUND_HALF_EVEN').copy()
"""Tests for the Australian Dollar representation."""
from multicurrency import AustralianDollar
class TestAustralianDollar:
"""AustralianDollar currency tests."""
def test_australian_dollar(self):
"""test_australian_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
australian_dollar = AustralianDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar.amount == decimal
assert australian_dollar.numeric_code == '036'
assert australian_dollar.alpha_code == 'AUD'
assert australian_dollar.decimal_places == 2
assert australian_dollar.decimal_sign == '.'
assert australian_dollar.grouping_places == 3
assert australian_dollar.grouping_sign == ','
assert not australian_dollar.international
assert australian_dollar.symbol == '$'
assert australian_dollar.symbol_ahead
assert australian_dollar.symbol_separator == ''
assert australian_dollar.localized_symbol == '$'
assert australian_dollar.convertion == ''
assert australian_dollar.__hash__() == hash(
(australian_dollar.__class__, decimal, 'AUD', '036'))
assert australian_dollar.__repr__() == (
'AustralianDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "$", '
'numeric_code: "036", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert australian_dollar.__str__() == '$0.14'
def test_australian_dollar_negative(self):
"""test_australian_dollar_negative."""
amount = -100
australian_dollar = AustralianDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar.numeric_code == '036'
assert australian_dollar.alpha_code == 'AUD'
assert australian_dollar.decimal_places == 2
assert australian_dollar.decimal_sign == '.'
assert australian_dollar.grouping_places == 3
assert australian_dollar.grouping_sign == ','
assert not australian_dollar.international
assert australian_dollar.symbol == '$'
assert australian_dollar.symbol_ahead
assert australian_dollar.symbol_separator == ''
assert australian_dollar.localized_symbol == '$'
assert australian_dollar.convertion == ''
assert australian_dollar.__hash__() == hash(
(australian_dollar.__class__, decimal, 'AUD', '036'))
assert australian_dollar.__repr__() == (
'AustralianDollar(amount: -100, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "$", '
'numeric_code: "036", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert australian_dollar.__str__() == '$-100.00'
def test_australian_dollar_custom(self):
"""test_australian_dollar_custom."""
amount = 1000
australian_dollar = AustralianDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar.amount == decimal
assert australian_dollar.numeric_code == '036'
assert australian_dollar.alpha_code == 'AUD'
assert australian_dollar.decimal_places == 5
assert australian_dollar.decimal_sign == ','
assert australian_dollar.grouping_places == 2
assert australian_dollar.grouping_sign == '.'
assert australian_dollar.international
assert australian_dollar.symbol == '$'
assert not australian_dollar.symbol_ahead
assert australian_dollar.symbol_separator == '_'
assert australian_dollar.localized_symbol == '$'
assert australian_dollar.convertion == ''
assert australian_dollar.__hash__() == hash(
(australian_dollar.__class__, decimal, 'AUD', '036'))
assert australian_dollar.__repr__() == (
'AustralianDollar(amount: 1000, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "$", '
'numeric_code: "036", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert australian_dollar.__str__() == 'AUD 10,00.00000'
def test_australian_dollar_changed(self):
"""test_caustralian_dollar_changed."""
australian_dollar = AustralianDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar.international = True
def test_australian_dollar_math_add(self):
"""test_australian_dollar_math_add."""
australian_dollar_one = AustralianDollar(amount=1)
australian_dollar_two = AustralianDollar(amount=2)
australian_dollar_three = AustralianDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency AUD and OTHER.'):
_ = australian_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.AustralianDollar\'> '
'and <class \'str\'>.')):
_ = australian_dollar_one.__add__('1.00')
assert (
australian_dollar_one +
australian_dollar_two) == australian_dollar_three
def test_australian_dollar_slots(self):
"""test_australian_dollar_slots."""
australian_dollar = AustralianDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'AustralianDollar\' '
'object has no attribute \'new_variable\'')):
australian_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Australian Dollar AU representation."""
from multicurrency import AustralianDollarAU
class TestAustralianDollarAU:
"""AustralianDollarAU currency tests."""
def test_australian_dollar_au(self):
"""test_australian_dollar_au."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
australian_dollar_au = AustralianDollarAU(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar_au.amount == decimal
assert australian_dollar_au.numeric_code == '036'
assert australian_dollar_au.alpha_code == 'AUD'
assert australian_dollar_au.decimal_places == 2
assert australian_dollar_au.decimal_sign == '.'
assert australian_dollar_au.grouping_places == 3
assert australian_dollar_au.grouping_sign == ','
assert not australian_dollar_au.international
assert australian_dollar_au.symbol == '$'
assert australian_dollar_au.symbol_ahead
assert australian_dollar_au.symbol_separator == ''
assert australian_dollar_au.localized_symbol == 'AU$'
assert australian_dollar_au.convertion == ''
assert australian_dollar_au.__hash__() == hash(
(australian_dollar_au.__class__, decimal, 'AUD', '036'))
assert australian_dollar_au.__repr__() == (
'AustralianDollarAU(amount: 0.1428571428571428571428571429, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "AU$", '
'numeric_code: "036", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert australian_dollar_au.__str__() == '$0.14'
def test_australian_dollar_au_negative(self):
"""test_australian_dollar_au_negative."""
amount = -100
australian_dollar_au = AustralianDollarAU(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar_au.numeric_code == '036'
assert australian_dollar_au.alpha_code == 'AUD'
assert australian_dollar_au.decimal_places == 2
assert australian_dollar_au.decimal_sign == '.'
assert australian_dollar_au.grouping_places == 3
assert australian_dollar_au.grouping_sign == ','
assert not australian_dollar_au.international
assert australian_dollar_au.symbol == '$'
assert australian_dollar_au.symbol_ahead
assert australian_dollar_au.symbol_separator == ''
assert australian_dollar_au.localized_symbol == 'AU$'
assert australian_dollar_au.convertion == ''
assert australian_dollar_au.__hash__() == hash(
(australian_dollar_au.__class__, decimal, 'AUD', '036'))
assert australian_dollar_au.__repr__() == (
'AustralianDollarAU(amount: -100, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "AU$", '
'numeric_code: "036", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert australian_dollar_au.__str__() == '$-100.00'
def test_australian_dollar_au_custom(self):
"""test_australian_dollar_au_custom."""
amount = 1000
australian_dollar_au = AustralianDollarAU(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar_au.amount == decimal
assert australian_dollar_au.numeric_code == '036'
assert australian_dollar_au.alpha_code == 'AUD'
assert australian_dollar_au.decimal_places == 5
assert australian_dollar_au.decimal_sign == ','
assert australian_dollar_au.grouping_places == 2
assert australian_dollar_au.grouping_sign == '.'
assert australian_dollar_au.international
assert australian_dollar_au.symbol == '$'
assert not australian_dollar_au.symbol_ahead
assert australian_dollar_au.symbol_separator == '_'
assert australian_dollar_au.localized_symbol == 'AU$'
assert australian_dollar_au.convertion == ''
assert australian_dollar_au.__hash__() == hash(
(australian_dollar_au.__class__, decimal, 'AUD', '036'))
assert australian_dollar_au.__repr__() == (
'AustralianDollarAU(amount: 1000, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "AU$", '
'numeric_code: "036", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert australian_dollar_au.__str__() == 'AUD 10,00.00000'
def test_australian_dollar_au_changed(self):
"""test_caustralian_dollar_au_changed."""
australian_dollar_au = AustralianDollarAU(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_au.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_au.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_au.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_au.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_au.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_au.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_au.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_au.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_au.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_au.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_au.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_au.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_au.international = True
def test_australian_dollar_au_math_add(self):
"""test_australian_dollar_au_math_add."""
australian_dollar_au_one = AustralianDollarAU(amount=1)
australian_dollar_au_two = AustralianDollarAU(amount=2)
australian_dollar_au_three = AustralianDollarAU(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency AUD and OTHER.'):
_ = australian_dollar_au_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.AustralianDollarAU\'> '
'and <class \'str\'>.')):
_ = australian_dollar_au_one.__add__('1.00')
assert (
australian_dollar_au_one +
australian_dollar_au_two) == australian_dollar_au_three
def test_australian_dollar_au_slots(self):
"""test_australian_dollar_au_slots."""
australian_dollar_au = AustralianDollarAU(amount=1000)
with raises(
AttributeError,
match=(
'\'AustralianDollarAU\' '
'object has no attribute \'new_variable\'')):
australian_dollar_au.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Australian Dollar KI representation."""
from multicurrency import AustralianDollarKI
class TestAustralianDollarKI:
"""AustralianDollarKI currency tests."""
def test_australian_dollar_ki(self):
"""test_australian_dollar_ki."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
australian_dollar_ki = AustralianDollarKI(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar_ki.amount == decimal
assert australian_dollar_ki.numeric_code == '036'
assert australian_dollar_ki.alpha_code == 'AUD'
assert australian_dollar_ki.decimal_places == 2
assert australian_dollar_ki.decimal_sign == '.'
assert australian_dollar_ki.grouping_places == 3
assert australian_dollar_ki.grouping_sign == ','
assert not australian_dollar_ki.international
assert australian_dollar_ki.symbol == '$'
assert australian_dollar_ki.symbol_ahead
assert australian_dollar_ki.symbol_separator == ''
assert australian_dollar_ki.localized_symbol == 'KI$'
assert australian_dollar_ki.convertion == ''
assert australian_dollar_ki.__hash__() == hash(
(australian_dollar_ki.__class__, decimal, 'AUD', '036'))
assert australian_dollar_ki.__repr__() == (
'AustralianDollarKI(amount: 0.1428571428571428571428571429, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "KI$", '
'numeric_code: "036", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert australian_dollar_ki.__str__() == '$0.14'
def test_australian_dollar_ki_negative(self):
"""test_australian_dollar_ki_negative."""
amount = -100
australian_dollar_ki = AustralianDollarKI(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar_ki.numeric_code == '036'
assert australian_dollar_ki.alpha_code == 'AUD'
assert australian_dollar_ki.decimal_places == 2
assert australian_dollar_ki.decimal_sign == '.'
assert australian_dollar_ki.grouping_places == 3
assert australian_dollar_ki.grouping_sign == ','
assert not australian_dollar_ki.international
assert australian_dollar_ki.symbol == '$'
assert australian_dollar_ki.symbol_ahead
assert australian_dollar_ki.symbol_separator == ''
assert australian_dollar_ki.localized_symbol == 'KI$'
assert australian_dollar_ki.convertion == ''
assert australian_dollar_ki.__hash__() == hash(
(australian_dollar_ki.__class__, decimal, 'AUD', '036'))
assert australian_dollar_ki.__repr__() == (
'AustralianDollarKI(amount: -100, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "KI$", '
'numeric_code: "036", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert australian_dollar_ki.__str__() == '$-100.00'
def test_australian_dollar_ki_custom(self):
"""test_australian_dollar_ki_custom."""
amount = 1000
australian_dollar_ki = AustralianDollarKI(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar_ki.amount == decimal
assert australian_dollar_ki.numeric_code == '036'
assert australian_dollar_ki.alpha_code == 'AUD'
assert australian_dollar_ki.decimal_places == 5
assert australian_dollar_ki.decimal_sign == ','
assert australian_dollar_ki.grouping_places == 2
assert australian_dollar_ki.grouping_sign == '.'
assert australian_dollar_ki.international
assert australian_dollar_ki.symbol == '$'
assert not australian_dollar_ki.symbol_ahead
assert australian_dollar_ki.symbol_separator == '_'
assert australian_dollar_ki.localized_symbol == 'KI$'
assert australian_dollar_ki.convertion == ''
assert australian_dollar_ki.__hash__() == hash(
(australian_dollar_ki.__class__, decimal, 'AUD', '036'))
assert australian_dollar_ki.__repr__() == (
'AustralianDollarKI(amount: 1000, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "KI$", '
'numeric_code: "036", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert australian_dollar_ki.__str__() == 'AUD 10,00.00000'
def test_australian_dollar_ki_changed(self):
"""test_caustralian_dollar_ki_changed."""
australian_dollar_ki = AustralianDollarKI(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_ki.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_ki.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_ki.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_ki.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_ki.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_ki.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_ki.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_ki.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_ki.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_ki.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_ki.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_ki.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_ki.international = True
def test_australian_dollar_ki_math_add(self):
"""test_australian_dollar_ki_math_add."""
australian_dollar_ki_one = AustralianDollarKI(amount=1)
australian_dollar_ki_two = AustralianDollarKI(amount=2)
australian_dollar_ki_three = AustralianDollarKI(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency AUD and OTHER.'):
_ = australian_dollar_ki_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.AustralianDollarKI\'> '
'and <class \'str\'>.')):
_ = australian_dollar_ki_one.__add__('1.00')
assert (
australian_dollar_ki_one +
australian_dollar_ki_two) == australian_dollar_ki_three
def test_australian_dollar_ki_slots(self):
"""test_australian_dollar_ki_slots."""
australian_dollar_ki = AustralianDollarKI(amount=1000)
with raises(
AttributeError,
match=(
'\'AustralianDollarKI\' '
'object has no attribute \'new_variable\'')):
australian_dollar_ki.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Australian Dollar CC representation."""
from multicurrency import AustralianDollarCC
class TestAustralianDollarCC:
"""AustralianDollarCC currency tests."""
def test_australian_dollar_cc(self):
"""test_australian_dollar_cc."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
australian_dollar_cc = AustralianDollarCC(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar_cc.amount == decimal
assert australian_dollar_cc.numeric_code == '036'
assert australian_dollar_cc.alpha_code == 'AUD'
assert australian_dollar_cc.decimal_places == 2
assert australian_dollar_cc.decimal_sign == '.'
assert australian_dollar_cc.grouping_places == 3
assert australian_dollar_cc.grouping_sign == ','
assert not australian_dollar_cc.international
assert australian_dollar_cc.symbol == '$'
assert australian_dollar_cc.symbol_ahead
assert australian_dollar_cc.symbol_separator == ''
assert australian_dollar_cc.localized_symbol == 'CC$'
assert australian_dollar_cc.convertion == ''
assert australian_dollar_cc.__hash__() == hash(
(australian_dollar_cc.__class__, decimal, 'AUD', '036'))
assert australian_dollar_cc.__repr__() == (
'AustralianDollarCC(amount: 0.1428571428571428571428571429, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "CC$", '
'numeric_code: "036", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert australian_dollar_cc.__str__() == '$0.14'
def test_australian_dollar_cc_negative(self):
"""test_australian_dollar_cc_negative."""
amount = -100
australian_dollar_cc = AustralianDollarCC(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar_cc.numeric_code == '036'
assert australian_dollar_cc.alpha_code == 'AUD'
assert australian_dollar_cc.decimal_places == 2
assert australian_dollar_cc.decimal_sign == '.'
assert australian_dollar_cc.grouping_places == 3
assert australian_dollar_cc.grouping_sign == ','
assert not australian_dollar_cc.international
assert australian_dollar_cc.symbol == '$'
assert australian_dollar_cc.symbol_ahead
assert australian_dollar_cc.symbol_separator == ''
assert australian_dollar_cc.localized_symbol == 'CC$'
assert australian_dollar_cc.convertion == ''
assert australian_dollar_cc.__hash__() == hash(
(australian_dollar_cc.__class__, decimal, 'AUD', '036'))
assert australian_dollar_cc.__repr__() == (
'AustralianDollarCC(amount: -100, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "CC$", '
'numeric_code: "036", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert australian_dollar_cc.__str__() == '$-100.00'
def test_australian_dollar_cc_custom(self):
"""test_australian_dollar_cc_custom."""
amount = 1000
australian_dollar_cc = AustralianDollarCC(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar_cc.amount == decimal
assert australian_dollar_cc.numeric_code == '036'
assert australian_dollar_cc.alpha_code == 'AUD'
assert australian_dollar_cc.decimal_places == 5
assert australian_dollar_cc.decimal_sign == ','
assert australian_dollar_cc.grouping_places == 2
assert australian_dollar_cc.grouping_sign == '.'
assert australian_dollar_cc.international
assert australian_dollar_cc.symbol == '$'
assert not australian_dollar_cc.symbol_ahead
assert australian_dollar_cc.symbol_separator == '_'
assert australian_dollar_cc.localized_symbol == 'CC$'
assert australian_dollar_cc.convertion == ''
assert australian_dollar_cc.__hash__() == hash(
(australian_dollar_cc.__class__, decimal, 'AUD', '036'))
assert australian_dollar_cc.__repr__() == (
'AustralianDollarCC(amount: 1000, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "CC$", '
'numeric_code: "036", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert australian_dollar_cc.__str__() == 'AUD 10,00.00000'
def test_australian_dollar_cc_changed(self):
"""test_caustralian_dollar_cc_changed."""
australian_dollar_cc = AustralianDollarCC(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_cc.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_cc.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_cc.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_cc.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_cc.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_cc.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_cc.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_cc.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_cc.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_cc.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_cc.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_cc.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_cc.international = True
def test_australian_dollar_cc_math_add(self):
"""test_australian_dollar_cc_math_add."""
australian_dollar_cc_one = AustralianDollarCC(amount=1)
australian_dollar_cc_two = AustralianDollarCC(amount=2)
australian_dollar_cc_three = AustralianDollarCC(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency AUD and OTHER.'):
_ = australian_dollar_cc_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.AustralianDollarCC\'> '
'and <class \'str\'>.')):
_ = australian_dollar_cc_one.__add__('1.00')
assert (
australian_dollar_cc_one +
australian_dollar_cc_two) == australian_dollar_cc_three
def test_australian_dollar_cc_slots(self):
"""test_australian_dollar_cc_slots."""
australian_dollar_cc = AustralianDollarCC(amount=1000)
with raises(
AttributeError,
match=(
'\'AustralianDollarCC\' '
'object has no attribute \'new_variable\'')):
australian_dollar_cc.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Australian Dollar MR representation."""
from multicurrency import AustralianDollarMR
class TestAustralianDollarMR:
"""AustralianDollarMR currency tests."""
def test_australian_dollar_mr(self):
"""test_australian_dollar_mr."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
australian_dollar_mr = AustralianDollarMR(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar_mr.amount == decimal
assert australian_dollar_mr.numeric_code == '036'
assert australian_dollar_mr.alpha_code == 'AUD'
assert australian_dollar_mr.decimal_places == 2
assert australian_dollar_mr.decimal_sign == '.'
assert australian_dollar_mr.grouping_places == 3
assert australian_dollar_mr.grouping_sign == ','
assert not australian_dollar_mr.international
assert australian_dollar_mr.symbol == '$'
assert australian_dollar_mr.symbol_ahead
assert australian_dollar_mr.symbol_separator == ''
assert australian_dollar_mr.localized_symbol == 'NR$'
assert australian_dollar_mr.convertion == ''
assert australian_dollar_mr.__hash__() == hash(
(australian_dollar_mr.__class__, decimal, 'AUD', '036'))
assert australian_dollar_mr.__repr__() == (
'AustralianDollarMR(amount: 0.1428571428571428571428571429, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "NR$", '
'numeric_code: "036", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert australian_dollar_mr.__str__() == '$0.14'
def test_australian_dollar_mr_negative(self):
"""test_australian_dollar_mr_negative."""
amount = -100
australian_dollar_mr = AustralianDollarMR(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar_mr.numeric_code == '036'
assert australian_dollar_mr.alpha_code == 'AUD'
assert australian_dollar_mr.decimal_places == 2
assert australian_dollar_mr.decimal_sign == '.'
assert australian_dollar_mr.grouping_places == 3
assert australian_dollar_mr.grouping_sign == ','
assert not australian_dollar_mr.international
assert australian_dollar_mr.symbol == '$'
assert australian_dollar_mr.symbol_ahead
assert australian_dollar_mr.symbol_separator == ''
assert australian_dollar_mr.localized_symbol == 'NR$'
assert australian_dollar_mr.convertion == ''
assert australian_dollar_mr.__hash__() == hash(
(australian_dollar_mr.__class__, decimal, 'AUD', '036'))
assert australian_dollar_mr.__repr__() == (
'AustralianDollarMR(amount: -100, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "NR$", '
'numeric_code: "036", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert australian_dollar_mr.__str__() == '$-100.00'
def test_australian_dollar_mr_custom(self):
"""test_australian_dollar_mr_custom."""
amount = 1000
australian_dollar_mr = AustralianDollarMR(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar_mr.amount == decimal
assert australian_dollar_mr.numeric_code == '036'
assert australian_dollar_mr.alpha_code == 'AUD'
assert australian_dollar_mr.decimal_places == 5
assert australian_dollar_mr.decimal_sign == ','
assert australian_dollar_mr.grouping_places == 2
assert australian_dollar_mr.grouping_sign == '.'
assert australian_dollar_mr.international
assert australian_dollar_mr.symbol == '$'
assert not australian_dollar_mr.symbol_ahead
assert australian_dollar_mr.symbol_separator == '_'
assert australian_dollar_mr.localized_symbol == 'NR$'
assert australian_dollar_mr.convertion == ''
assert australian_dollar_mr.__hash__() == hash(
(australian_dollar_mr.__class__, decimal, 'AUD', '036'))
assert australian_dollar_mr.__repr__() == (
'AustralianDollarMR(amount: 1000, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "NR$", '
'numeric_code: "036", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert australian_dollar_mr.__str__() == 'AUD 10,00.00000'
def test_australian_dollar_mr_changed(self):
"""test_caustralian_dollar_mr_changed."""
australian_dollar_mr = AustralianDollarMR(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_mr.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_mr.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_mr.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_mr.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_mr.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_mr.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_mr.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_mr.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_mr.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_mr.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_mr.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_mr.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_mr.international = True
def test_australian_dollar_mr_math_add(self):
"""test_australian_dollar_mr_math_add."""
australian_dollar_mr_one = AustralianDollarMR(amount=1)
australian_dollar_mr_two = AustralianDollarMR(amount=2)
australian_dollar_mr_three = AustralianDollarMR(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency AUD and OTHER.'):
_ = australian_dollar_mr_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.AustralianDollarMR\'> '
'and <class \'str\'>.')):
_ = australian_dollar_mr_one.__add__('1.00')
assert (
australian_dollar_mr_one +
australian_dollar_mr_two) == australian_dollar_mr_three
def test_australian_dollar_mr_slots(self):
"""test_australian_dollar_mr_slots."""
australian_dollar_mr = AustralianDollarMR(amount=1000)
with raises(
AttributeError,
match=(
'\'AustralianDollarMR\' '
'object has no attribute \'new_variable\'')):
australian_dollar_mr.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Australian Dollar TV representation."""
from multicurrency import AustralianDollarTV
class TestAustralianDollarTV:
"""AustralianDollarTV currency tests."""
def test_australian_dollar_tv(self):
"""test_australian_dollar_tv."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
australian_dollar_tv = AustralianDollarTV(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar_tv.amount == decimal
assert australian_dollar_tv.numeric_code == '036'
assert australian_dollar_tv.alpha_code == 'AUD'
assert australian_dollar_tv.decimal_places == 2
assert australian_dollar_tv.decimal_sign == '.'
assert australian_dollar_tv.grouping_places == 3
assert australian_dollar_tv.grouping_sign == ','
assert not australian_dollar_tv.international
assert australian_dollar_tv.symbol == '$'
assert australian_dollar_tv.symbol_ahead
assert australian_dollar_tv.symbol_separator == ''
assert australian_dollar_tv.localized_symbol == 'TV$'
assert australian_dollar_tv.convertion == ''
assert australian_dollar_tv.__hash__() == hash(
(australian_dollar_tv.__class__, decimal, 'AUD', '036'))
assert australian_dollar_tv.__repr__() == (
'AustralianDollarTV(amount: 0.1428571428571428571428571429, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "TV$", '
'numeric_code: "036", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert australian_dollar_tv.__str__() == '$0.14'
def test_australian_dollar_tv_negative(self):
"""test_australian_dollar_tv_negative."""
amount = -100
australian_dollar_tv = AustralianDollarTV(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar_tv.numeric_code == '036'
assert australian_dollar_tv.alpha_code == 'AUD'
assert australian_dollar_tv.decimal_places == 2
assert australian_dollar_tv.decimal_sign == '.'
assert australian_dollar_tv.grouping_places == 3
assert australian_dollar_tv.grouping_sign == ','
assert not australian_dollar_tv.international
assert australian_dollar_tv.symbol == '$'
assert australian_dollar_tv.symbol_ahead
assert australian_dollar_tv.symbol_separator == ''
assert australian_dollar_tv.localized_symbol == 'TV$'
assert australian_dollar_tv.convertion == ''
assert australian_dollar_tv.__hash__() == hash(
(australian_dollar_tv.__class__, decimal, 'AUD', '036'))
assert australian_dollar_tv.__repr__() == (
'AustralianDollarTV(amount: -100, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "TV$", '
'numeric_code: "036", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert australian_dollar_tv.__str__() == '$-100.00'
def test_australian_dollar_tv_custom(self):
"""test_australian_dollar_tv_custom."""
amount = 1000
australian_dollar_tv = AustralianDollarTV(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert australian_dollar_tv.amount == decimal
assert australian_dollar_tv.numeric_code == '036'
assert australian_dollar_tv.alpha_code == 'AUD'
assert australian_dollar_tv.decimal_places == 5
assert australian_dollar_tv.decimal_sign == ','
assert australian_dollar_tv.grouping_places == 2
assert australian_dollar_tv.grouping_sign == '.'
assert australian_dollar_tv.international
assert australian_dollar_tv.symbol == '$'
assert not australian_dollar_tv.symbol_ahead
assert australian_dollar_tv.symbol_separator == '_'
assert australian_dollar_tv.localized_symbol == 'TV$'
assert australian_dollar_tv.convertion == ''
assert australian_dollar_tv.__hash__() == hash(
(australian_dollar_tv.__class__, decimal, 'AUD', '036'))
assert australian_dollar_tv.__repr__() == (
'AustralianDollarTV(amount: 1000, '
'alpha_code: "AUD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "TV$", '
'numeric_code: "036", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert australian_dollar_tv.__str__() == 'AUD 10,00.00000'
def test_australian_dollar_tv_changed(self):
"""test_caustralian_dollar_tv_changed."""
australian_dollar_tv = AustralianDollarTV(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_tv.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_tv.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_tv.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_tv.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_tv.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_tv.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_tv.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_tv.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_tv.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_tv.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_tv.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_tv.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
australian_dollar_tv.international = True
def test_australian_dollar_tv_math_add(self):
"""test_australian_dollar_tv_math_add."""
australian_dollar_tv_one = AustralianDollarTV(amount=1)
australian_dollar_tv_two = AustralianDollarTV(amount=2)
australian_dollar_tv_three = AustralianDollarTV(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency AUD and OTHER.'):
_ = australian_dollar_tv_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.AustralianDollarTV\'> '
'and <class \'str\'>.')):
_ = australian_dollar_tv_one.__add__('1.00')
assert (
australian_dollar_tv_one +
australian_dollar_tv_two) == australian_dollar_tv_three
def test_australian_dollar_tv_slots(self):
"""test_australian_dollar_tv_slots."""
australian_dollar_tv = AustralianDollarTV(amount=1000)
with raises(
AttributeError,
match=(
'\'AustralianDollarTV\' '
'object has no attribute \'new_variable\'')):
australian_dollar_tv.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Barbados Dollar representation."""
from multicurrency import BarbadosDollar
class TestBarbadosDollar:
"""BarbadosDollar currency tests."""
def test_barbados_dollar(self):
"""test_barbados_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
barbados_dollar = BarbadosDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert barbados_dollar.amount == decimal
assert barbados_dollar.numeric_code == '052'
assert barbados_dollar.alpha_code == 'BBD'
assert barbados_dollar.decimal_places == 2
assert barbados_dollar.decimal_sign == '.'
assert barbados_dollar.grouping_places == 3
assert barbados_dollar.grouping_sign == ','
assert not barbados_dollar.international
assert barbados_dollar.symbol == '$'
assert barbados_dollar.symbol_ahead
assert barbados_dollar.symbol_separator == ''
assert barbados_dollar.localized_symbol == 'BB$'
assert barbados_dollar.convertion == ''
assert barbados_dollar.__hash__() == hash(
(barbados_dollar.__class__, decimal, 'BBD', '052'))
assert barbados_dollar.__repr__() == (
'BarbadosDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "BBD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "BB$", '
'numeric_code: "052", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert barbados_dollar.__str__() == '$0.14'
def test_barbados_dollar_negative(self):
"""test_barbados_dollar_negative."""
amount = -100
barbados_dollar = BarbadosDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert barbados_dollar.numeric_code == '052'
assert barbados_dollar.alpha_code == 'BBD'
assert barbados_dollar.decimal_places == 2
assert barbados_dollar.decimal_sign == '.'
assert barbados_dollar.grouping_places == 3
assert barbados_dollar.grouping_sign == ','
assert not barbados_dollar.international
assert barbados_dollar.symbol == '$'
assert barbados_dollar.symbol_ahead
assert barbados_dollar.symbol_separator == ''
assert barbados_dollar.localized_symbol == 'BB$'
assert barbados_dollar.convertion == ''
assert barbados_dollar.__hash__() == hash(
(barbados_dollar.__class__, decimal, 'BBD', '052'))
assert barbados_dollar.__repr__() == (
'BarbadosDollar(amount: -100, '
'alpha_code: "BBD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "BB$", '
'numeric_code: "052", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert barbados_dollar.__str__() == '$-100.00'
def test_barbados_dollar_custom(self):
"""test_barbados_dollar_custom."""
amount = 1000
barbados_dollar = BarbadosDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert barbados_dollar.amount == decimal
assert barbados_dollar.numeric_code == '052'
assert barbados_dollar.alpha_code == 'BBD'
assert barbados_dollar.decimal_places == 5
assert barbados_dollar.decimal_sign == ','
assert barbados_dollar.grouping_places == 2
assert barbados_dollar.grouping_sign == '.'
assert barbados_dollar.international
assert barbados_dollar.symbol == '$'
assert not barbados_dollar.symbol_ahead
assert barbados_dollar.symbol_separator == '_'
assert barbados_dollar.localized_symbol == 'BB$'
assert barbados_dollar.convertion == ''
assert barbados_dollar.__hash__() == hash(
(barbados_dollar.__class__, decimal, 'BBD', '052'))
assert barbados_dollar.__repr__() == (
'BarbadosDollar(amount: 1000, '
'alpha_code: "BBD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "BB$", '
'numeric_code: "052", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert barbados_dollar.__str__() == 'BBD 10,00.00000'
def test_barbados_dollar_changed(self):
"""test_cbarbados_dollar_changed."""
barbados_dollar = BarbadosDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
barbados_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
barbados_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
barbados_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
barbados_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
barbados_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
barbados_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
barbados_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
barbados_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
barbados_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
barbados_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
barbados_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
barbados_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
barbados_dollar.international = True
def test_barbados_dollar_math_add(self):
"""test_barbados_dollar_math_add."""
barbados_dollar_one = BarbadosDollar(amount=1)
barbados_dollar_two = BarbadosDollar(amount=2)
barbados_dollar_three = BarbadosDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency BBD and OTHER.'):
_ = barbados_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.BarbadosDollar\'> '
'and <class \'str\'>.')):
_ = barbados_dollar_one.__add__('1.00')
assert (
barbados_dollar_one +
barbados_dollar_two) == barbados_dollar_three
def test_barbados_dollar_slots(self):
"""test_barbados_dollar_slots."""
barbados_dollar = BarbadosDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'BarbadosDollar\' '
'object has no attribute \'new_variable\'')):
barbados_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Bermudian Dollar representation."""
from multicurrency import BermudianDollar
class TestBermudianDollar:
"""BermudianDollar currency tests."""
def test_bermudian_dollar(self):
"""test_bermudian_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
bermudian_dollar = BermudianDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert bermudian_dollar.amount == decimal
assert bermudian_dollar.numeric_code == '060'
assert bermudian_dollar.alpha_code == 'BMD'
assert bermudian_dollar.decimal_places == 2
assert bermudian_dollar.decimal_sign == '.'
assert bermudian_dollar.grouping_places == 3
assert bermudian_dollar.grouping_sign == ','
assert not bermudian_dollar.international
assert bermudian_dollar.symbol == '$'
assert bermudian_dollar.symbol_ahead
assert bermudian_dollar.symbol_separator == ''
assert bermudian_dollar.localized_symbol == 'BM$'
assert bermudian_dollar.convertion == ''
assert bermudian_dollar.__hash__() == hash(
(bermudian_dollar.__class__, decimal, 'BMD', '060'))
assert bermudian_dollar.__repr__() == (
'BermudianDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "BMD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "BM$", '
'numeric_code: "060", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert bermudian_dollar.__str__() == '$0.14'
def test_bermudian_dollar_negative(self):
"""test_bermudian_dollar_negative."""
amount = -100
bermudian_dollar = BermudianDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert bermudian_dollar.numeric_code == '060'
assert bermudian_dollar.alpha_code == 'BMD'
assert bermudian_dollar.decimal_places == 2
assert bermudian_dollar.decimal_sign == '.'
assert bermudian_dollar.grouping_places == 3
assert bermudian_dollar.grouping_sign == ','
assert not bermudian_dollar.international
assert bermudian_dollar.symbol == '$'
assert bermudian_dollar.symbol_ahead
assert bermudian_dollar.symbol_separator == ''
assert bermudian_dollar.localized_symbol == 'BM$'
assert bermudian_dollar.convertion == ''
assert bermudian_dollar.__hash__() == hash(
(bermudian_dollar.__class__, decimal, 'BMD', '060'))
assert bermudian_dollar.__repr__() == (
'BermudianDollar(amount: -100, '
'alpha_code: "BMD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "BM$", '
'numeric_code: "060", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert bermudian_dollar.__str__() == '$-100.00'
def test_bermudian_dollar_custom(self):
"""test_bermudian_dollar_custom."""
amount = 1000
bermudian_dollar = BermudianDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert bermudian_dollar.amount == decimal
assert bermudian_dollar.numeric_code == '060'
assert bermudian_dollar.alpha_code == 'BMD'
assert bermudian_dollar.decimal_places == 5
assert bermudian_dollar.decimal_sign == ','
assert bermudian_dollar.grouping_places == 2
assert bermudian_dollar.grouping_sign == '.'
assert bermudian_dollar.international
assert bermudian_dollar.symbol == '$'
assert not bermudian_dollar.symbol_ahead
assert bermudian_dollar.symbol_separator == '_'
assert bermudian_dollar.localized_symbol == 'BM$'
assert bermudian_dollar.convertion == ''
assert bermudian_dollar.__hash__() == hash(
(bermudian_dollar.__class__, decimal, 'BMD', '060'))
assert bermudian_dollar.__repr__() == (
'BermudianDollar(amount: 1000, '
'alpha_code: "BMD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "BM$", '
'numeric_code: "060", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert bermudian_dollar.__str__() == 'BMD 10,00.00000'
def test_bermudian_dollar_changed(self):
"""test_cbermudian_dollar_changed."""
bermudian_dollar = BermudianDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
bermudian_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
bermudian_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
bermudian_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
bermudian_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
bermudian_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
bermudian_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
bermudian_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
bermudian_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
bermudian_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
bermudian_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
bermudian_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
bermudian_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
bermudian_dollar.international = True
def test_bermudian_dollar_math_add(self):
"""test_bermudian_dollar_math_add."""
bermudian_dollar_one = BermudianDollar(amount=1)
bermudian_dollar_two = BermudianDollar(amount=2)
bermudian_dollar_three = BermudianDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency BMD and OTHER.'):
_ = bermudian_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.BermudianDollar\'> '
'and <class \'str\'>.')):
_ = bermudian_dollar_one.__add__('1.00')
assert (
bermudian_dollar_one +
bermudian_dollar_two) == bermudian_dollar_three
def test_bermudian_dollar_slots(self):
"""test_bermudian_dollar_slots."""
bermudian_dollar = BermudianDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'BermudianDollar\' '
'object has no attribute \'new_variable\'')):
bermudian_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Brunei Dollar representation."""
from multicurrency import BruneiDollar
class TestBruneiDollar:
"""BruneiDollar currency tests."""
def test_brunei_dollar(self):
"""test_brunei_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
brunei_dollar = BruneiDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert brunei_dollar.amount == decimal
assert brunei_dollar.numeric_code == '096'
assert brunei_dollar.alpha_code == 'BND'
assert brunei_dollar.decimal_places == 2
assert brunei_dollar.decimal_sign == ','
assert brunei_dollar.grouping_places == 3
assert brunei_dollar.grouping_sign == '.'
assert not brunei_dollar.international
assert brunei_dollar.symbol == '$'
assert brunei_dollar.symbol_ahead
assert brunei_dollar.symbol_separator == '\u00A0'
assert brunei_dollar.localized_symbol == '$'
assert brunei_dollar.convertion == ''
assert brunei_dollar.__hash__() == hash(
(brunei_dollar.__class__, decimal, 'BND', '096'))
assert brunei_dollar.__repr__() == (
'BruneiDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "BND", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "\u00A0", '
'localized_symbol: "$", '
'numeric_code: "096", '
'decimal_places: "2", '
'decimal_sign: ",", '
'grouping_places: "3", '
'grouping_sign: ".", '
'convertion: "", '
'international: False)')
assert brunei_dollar.__str__() == '$ 0,14'
def test_brunei_dollar_negative(self):
"""test_brunei_dollar_negative."""
amount = -100
brunei_dollar = BruneiDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert brunei_dollar.numeric_code == '096'
assert brunei_dollar.alpha_code == 'BND'
assert brunei_dollar.decimal_places == 2
assert brunei_dollar.decimal_sign == ','
assert brunei_dollar.grouping_places == 3
assert brunei_dollar.grouping_sign == '.'
assert not brunei_dollar.international
assert brunei_dollar.symbol == '$'
assert brunei_dollar.symbol_ahead
assert brunei_dollar.symbol_separator == '\u00A0'
assert brunei_dollar.localized_symbol == '$'
assert brunei_dollar.convertion == ''
assert brunei_dollar.__hash__() == hash(
(brunei_dollar.__class__, decimal, 'BND', '096'))
assert brunei_dollar.__repr__() == (
'BruneiDollar(amount: -100, '
'alpha_code: "BND", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "\u00A0", '
'localized_symbol: "$", '
'numeric_code: "096", '
'decimal_places: "2", '
'decimal_sign: ",", '
'grouping_places: "3", '
'grouping_sign: ".", '
'convertion: "", '
'international: False)')
assert brunei_dollar.__str__() == '$ -100,00'
def test_brunei_dollar_custom(self):
"""test_brunei_dollar_custom."""
amount = 1000
brunei_dollar = BruneiDollar(
amount=amount,
decimal_places=5,
decimal_sign='.',
grouping_places=2,
grouping_sign=',',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert brunei_dollar.amount == decimal
assert brunei_dollar.numeric_code == '096'
assert brunei_dollar.alpha_code == 'BND'
assert brunei_dollar.decimal_places == 5
assert brunei_dollar.decimal_sign == '.'
assert brunei_dollar.grouping_places == 2
assert brunei_dollar.grouping_sign == ','
assert brunei_dollar.international
assert brunei_dollar.symbol == '$'
assert not brunei_dollar.symbol_ahead
assert brunei_dollar.symbol_separator == '_'
assert brunei_dollar.localized_symbol == '$'
assert brunei_dollar.convertion == ''
assert brunei_dollar.__hash__() == hash(
(brunei_dollar.__class__, decimal, 'BND', '096'))
assert brunei_dollar.__repr__() == (
'BruneiDollar(amount: 1000, '
'alpha_code: "BND", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "$", '
'numeric_code: "096", '
'decimal_places: "5", '
'decimal_sign: ".", '
'grouping_places: "2", '
'grouping_sign: ",", '
'convertion: "", '
'international: True)')
assert brunei_dollar.__str__() == 'BND 10,00.00000'
def test_brunei_dollar_changed(self):
"""test_cbrunei_dollar_changed."""
brunei_dollar = BruneiDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar.international = True
def test_brunei_dollar_math_add(self):
"""test_brunei_dollar_math_add."""
brunei_dollar_one = BruneiDollar(amount=1)
brunei_dollar_two = BruneiDollar(amount=2)
brunei_dollar_three = BruneiDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency BND and OTHER.'):
_ = brunei_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.BruneiDollar\'> '
'and <class \'str\'>.')):
_ = brunei_dollar_one.__add__('1.00')
assert (
brunei_dollar_one +
brunei_dollar_two) == brunei_dollar_three
def test_brunei_dollar_slots(self):
"""test_brunei_dollar_slots."""
brunei_dollar = BruneiDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'BruneiDollar\' '
'object has no attribute \'new_variable\'')):
brunei_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Brunei Dollar BN representation."""
from multicurrency import BruneiDollarBN
class TestBruneiDollarBN:
"""BruneiDollarBN currency tests."""
def test_brunei_dollar_bn(self):
"""test_brunei_dollar_bn."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
brunei_dollar_bn = BruneiDollarBN(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert brunei_dollar_bn.amount == decimal
assert brunei_dollar_bn.numeric_code == '096'
assert brunei_dollar_bn.alpha_code == 'BND'
assert brunei_dollar_bn.decimal_places == 2
assert brunei_dollar_bn.decimal_sign == ','
assert brunei_dollar_bn.grouping_places == 3
assert brunei_dollar_bn.grouping_sign == '.'
assert not brunei_dollar_bn.international
assert brunei_dollar_bn.symbol == '$'
assert brunei_dollar_bn.symbol_ahead
assert brunei_dollar_bn.symbol_separator == '\u00A0'
assert brunei_dollar_bn.localized_symbol == 'BN$'
assert brunei_dollar_bn.convertion == ''
assert brunei_dollar_bn.__hash__() == hash(
(brunei_dollar_bn.__class__, decimal, 'BND', '096'))
assert brunei_dollar_bn.__repr__() == (
'BruneiDollarBN(amount: 0.1428571428571428571428571429, '
'alpha_code: "BND", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "\u00A0", '
'localized_symbol: "BN$", '
'numeric_code: "096", '
'decimal_places: "2", '
'decimal_sign: ",", '
'grouping_places: "3", '
'grouping_sign: ".", '
'convertion: "", '
'international: False)')
assert brunei_dollar_bn.__str__() == '$ 0,14'
def test_brunei_dollar_bn_negative(self):
"""test_brunei_dollar_bn_negative."""
amount = -100
brunei_dollar_bn = BruneiDollarBN(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert brunei_dollar_bn.numeric_code == '096'
assert brunei_dollar_bn.alpha_code == 'BND'
assert brunei_dollar_bn.decimal_places == 2
assert brunei_dollar_bn.decimal_sign == ','
assert brunei_dollar_bn.grouping_places == 3
assert brunei_dollar_bn.grouping_sign == '.'
assert not brunei_dollar_bn.international
assert brunei_dollar_bn.symbol == '$'
assert brunei_dollar_bn.symbol_ahead
assert brunei_dollar_bn.symbol_separator == '\u00A0'
assert brunei_dollar_bn.localized_symbol == 'BN$'
assert brunei_dollar_bn.convertion == ''
assert brunei_dollar_bn.__hash__() == hash(
(brunei_dollar_bn.__class__, decimal, 'BND', '096'))
assert brunei_dollar_bn.__repr__() == (
'BruneiDollarBN(amount: -100, '
'alpha_code: "BND", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "\u00A0", '
'localized_symbol: "BN$", '
'numeric_code: "096", '
'decimal_places: "2", '
'decimal_sign: ",", '
'grouping_places: "3", '
'grouping_sign: ".", '
'convertion: "", '
'international: False)')
assert brunei_dollar_bn.__str__() == '$ -100,00'
def test_brunei_dollar_bn_custom(self):
"""test_brunei_dollar_bn_custom."""
amount = 1000
brunei_dollar_bn = BruneiDollarBN(
amount=amount,
decimal_places=5,
decimal_sign='.',
grouping_places=2,
grouping_sign=',',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert brunei_dollar_bn.amount == decimal
assert brunei_dollar_bn.numeric_code == '096'
assert brunei_dollar_bn.alpha_code == 'BND'
assert brunei_dollar_bn.decimal_places == 5
assert brunei_dollar_bn.decimal_sign == '.'
assert brunei_dollar_bn.grouping_places == 2
assert brunei_dollar_bn.grouping_sign == ','
assert brunei_dollar_bn.international
assert brunei_dollar_bn.symbol == '$'
assert not brunei_dollar_bn.symbol_ahead
assert brunei_dollar_bn.symbol_separator == '_'
assert brunei_dollar_bn.localized_symbol == 'BN$'
assert brunei_dollar_bn.convertion == ''
assert brunei_dollar_bn.__hash__() == hash(
(brunei_dollar_bn.__class__, decimal, 'BND', '096'))
assert brunei_dollar_bn.__repr__() == (
'BruneiDollarBN(amount: 1000, '
'alpha_code: "BND", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "BN$", '
'numeric_code: "096", '
'decimal_places: "5", '
'decimal_sign: ".", '
'grouping_places: "2", '
'grouping_sign: ",", '
'convertion: "", '
'international: True)')
assert brunei_dollar_bn.__str__() == 'BND 10,00.00000'
def test_brunei_dollar_bn_changed(self):
"""test_cbrunei_dollar_bn_changed."""
brunei_dollar_bn = BruneiDollarBN(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_bn.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_bn.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_bn.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_bn.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_bn.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_bn.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_bn.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_bn.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_bn.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_bn.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_bn.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_bn.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_bn.international = True
def test_brunei_dollar_bn_math_add(self):
"""test_brunei_dollar_bn_math_add."""
brunei_dollar_bn_one = BruneiDollarBN(amount=1)
brunei_dollar_bn_two = BruneiDollarBN(amount=2)
brunei_dollar_bn_three = BruneiDollarBN(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency BND and OTHER.'):
_ = brunei_dollar_bn_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.BruneiDollarBN\'> '
'and <class \'str\'>.')):
_ = brunei_dollar_bn_one.__add__('1.00')
assert (
brunei_dollar_bn_one +
brunei_dollar_bn_two) == brunei_dollar_bn_three
def test_brunei_dollar_bn_slots(self):
"""test_brunei_dollar_bn_slots."""
brunei_dollar_bn = BruneiDollarBN(amount=1000)
with raises(
AttributeError,
match=(
'\'BruneiDollarBN\' '
'object has no attribute \'new_variable\'')):
brunei_dollar_bn.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Brunei Dollar SG representation."""
from multicurrency import BruneiDollarSG
class TestBruneiDollarSG:
"""BruneiDollarSG currency tests."""
def test_brunei_dollar_sg(self):
"""test_brunei_dollar_sg."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
brunei_dollar_sg = BruneiDollarSG(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert brunei_dollar_sg.amount == decimal
assert brunei_dollar_sg.numeric_code == '096'
assert brunei_dollar_sg.alpha_code == 'BND'
assert brunei_dollar_sg.decimal_places == 2
assert brunei_dollar_sg.decimal_sign == ','
assert brunei_dollar_sg.grouping_places == 3
assert brunei_dollar_sg.grouping_sign == '.'
assert not brunei_dollar_sg.international
assert brunei_dollar_sg.symbol == '$'
assert brunei_dollar_sg.symbol_ahead
assert brunei_dollar_sg.symbol_separator == '\u00A0'
assert brunei_dollar_sg.localized_symbol == 'SG$'
assert brunei_dollar_sg.convertion == ''
assert brunei_dollar_sg.__hash__() == hash(
(brunei_dollar_sg.__class__, decimal, 'BND', '096'))
assert brunei_dollar_sg.__repr__() == (
'BruneiDollarSG(amount: 0.1428571428571428571428571429, '
'alpha_code: "BND", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "\u00A0", '
'localized_symbol: "SG$", '
'numeric_code: "096", '
'decimal_places: "2", '
'decimal_sign: ",", '
'grouping_places: "3", '
'grouping_sign: ".", '
'convertion: "", '
'international: False)')
assert brunei_dollar_sg.__str__() == '$ 0,14'
def test_brunei_dollar_sg_negative(self):
"""test_brunei_dollar_sg_negative."""
amount = -100
brunei_dollar_sg = BruneiDollarSG(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert brunei_dollar_sg.numeric_code == '096'
assert brunei_dollar_sg.alpha_code == 'BND'
assert brunei_dollar_sg.decimal_places == 2
assert brunei_dollar_sg.decimal_sign == ','
assert brunei_dollar_sg.grouping_places == 3
assert brunei_dollar_sg.grouping_sign == '.'
assert not brunei_dollar_sg.international
assert brunei_dollar_sg.symbol == '$'
assert brunei_dollar_sg.symbol_ahead
assert brunei_dollar_sg.symbol_separator == '\u00A0'
assert brunei_dollar_sg.localized_symbol == 'SG$'
assert brunei_dollar_sg.convertion == ''
assert brunei_dollar_sg.__hash__() == hash(
(brunei_dollar_sg.__class__, decimal, 'BND', '096'))
assert brunei_dollar_sg.__repr__() == (
'BruneiDollarSG(amount: -100, '
'alpha_code: "BND", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "\u00A0", '
'localized_symbol: "SG$", '
'numeric_code: "096", '
'decimal_places: "2", '
'decimal_sign: ",", '
'grouping_places: "3", '
'grouping_sign: ".", '
'convertion: "", '
'international: False)')
assert brunei_dollar_sg.__str__() == '$ -100,00'
def test_brunei_dollar_sg_custom(self):
"""test_brunei_dollar_sg_custom."""
amount = 1000
brunei_dollar_sg = BruneiDollarSG(
amount=amount,
decimal_places=5,
decimal_sign='.',
grouping_places=2,
grouping_sign=',',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert brunei_dollar_sg.amount == decimal
assert brunei_dollar_sg.numeric_code == '096'
assert brunei_dollar_sg.alpha_code == 'BND'
assert brunei_dollar_sg.decimal_places == 5
assert brunei_dollar_sg.decimal_sign == '.'
assert brunei_dollar_sg.grouping_places == 2
assert brunei_dollar_sg.grouping_sign == ','
assert brunei_dollar_sg.international
assert brunei_dollar_sg.symbol == '$'
assert not brunei_dollar_sg.symbol_ahead
assert brunei_dollar_sg.symbol_separator == '_'
assert brunei_dollar_sg.localized_symbol == 'SG$'
assert brunei_dollar_sg.convertion == ''
assert brunei_dollar_sg.__hash__() == hash(
(brunei_dollar_sg.__class__, decimal, 'BND', '096'))
assert brunei_dollar_sg.__repr__() == (
'BruneiDollarSG(amount: 1000, '
'alpha_code: "BND", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "SG$", '
'numeric_code: "096", '
'decimal_places: "5", '
'decimal_sign: ".", '
'grouping_places: "2", '
'grouping_sign: ",", '
'convertion: "", '
'international: True)')
assert brunei_dollar_sg.__str__() == 'BND 10,00.00000'
def test_brunei_dollar_sg_changed(self):
"""test_cbrunei_dollar_sg_changed."""
brunei_dollar_sg = BruneiDollarSG(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_sg.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_sg.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_sg.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_sg.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_sg.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_sg.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_sg.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_sg.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_sg.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_sg.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_sg.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_sg.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
brunei_dollar_sg.international = True
def test_brunei_dollar_sg_math_add(self):
"""test_brunei_dollar_sg_math_add."""
brunei_dollar_sg_one = BruneiDollarSG(amount=1)
brunei_dollar_sg_two = BruneiDollarSG(amount=2)
brunei_dollar_sg_three = BruneiDollarSG(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency BND and OTHER.'):
_ = brunei_dollar_sg_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.BruneiDollarSG\'> '
'and <class \'str\'>.')):
_ = brunei_dollar_sg_one.__add__('1.00')
assert (
brunei_dollar_sg_one +
brunei_dollar_sg_two) == brunei_dollar_sg_three
def test_brunei_dollar_sg_slots(self):
"""test_brunei_dollar_sg_slots."""
brunei_dollar_sg = BruneiDollarSG(amount=1000)
with raises(
AttributeError,
match=(
'\'BruneiDollarSG\' '
'object has no attribute \'new_variable\'')):
brunei_dollar_sg.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Bahamian Dollar representation."""
from multicurrency import BahamianDollar
class TestBahamianDollar:
"""BahamianDollar currency tests."""
def test_bahamian_dollar(self):
"""test_bahamian_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
bahamian_dollar = BahamianDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert bahamian_dollar.amount == decimal
assert bahamian_dollar.numeric_code == '044'
assert bahamian_dollar.alpha_code == 'BSD'
assert bahamian_dollar.decimal_places == 2
assert bahamian_dollar.decimal_sign == '.'
assert bahamian_dollar.grouping_places == 3
assert bahamian_dollar.grouping_sign == ','
assert not bahamian_dollar.international
assert bahamian_dollar.symbol == '$'
assert bahamian_dollar.symbol_ahead
assert bahamian_dollar.symbol_separator == ''
assert bahamian_dollar.localized_symbol == 'BS$'
assert bahamian_dollar.convertion == ''
assert bahamian_dollar.__hash__() == hash(
(bahamian_dollar.__class__, decimal, 'BSD', '044'))
assert bahamian_dollar.__repr__() == (
'BahamianDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "BSD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "BS$", '
'numeric_code: "044", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert bahamian_dollar.__str__() == '$0.14'
def test_bahamian_dollar_negative(self):
"""test_bahamian_dollar_negative."""
amount = -100
bahamian_dollar = BahamianDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert bahamian_dollar.numeric_code == '044'
assert bahamian_dollar.alpha_code == 'BSD'
assert bahamian_dollar.decimal_places == 2
assert bahamian_dollar.decimal_sign == '.'
assert bahamian_dollar.grouping_places == 3
assert bahamian_dollar.grouping_sign == ','
assert not bahamian_dollar.international
assert bahamian_dollar.symbol == '$'
assert bahamian_dollar.symbol_ahead
assert bahamian_dollar.symbol_separator == ''
assert bahamian_dollar.localized_symbol == 'BS$'
assert bahamian_dollar.convertion == ''
assert bahamian_dollar.__hash__() == hash(
(bahamian_dollar.__class__, decimal, 'BSD', '044'))
assert bahamian_dollar.__repr__() == (
'BahamianDollar(amount: -100, '
'alpha_code: "BSD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "BS$", '
'numeric_code: "044", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert bahamian_dollar.__str__() == '$-100.00'
def test_bahamian_dollar_custom(self):
"""test_bahamian_dollar_custom."""
amount = 1000
bahamian_dollar = BahamianDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert bahamian_dollar.amount == decimal
assert bahamian_dollar.numeric_code == '044'
assert bahamian_dollar.alpha_code == 'BSD'
assert bahamian_dollar.decimal_places == 5
assert bahamian_dollar.decimal_sign == ','
assert bahamian_dollar.grouping_places == 2
assert bahamian_dollar.grouping_sign == '.'
assert bahamian_dollar.international
assert bahamian_dollar.symbol == '$'
assert not bahamian_dollar.symbol_ahead
assert bahamian_dollar.symbol_separator == '_'
assert bahamian_dollar.localized_symbol == 'BS$'
assert bahamian_dollar.convertion == ''
assert bahamian_dollar.__hash__() == hash(
(bahamian_dollar.__class__, decimal, 'BSD', '044'))
assert bahamian_dollar.__repr__() == (
'BahamianDollar(amount: 1000, '
'alpha_code: "BSD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "BS$", '
'numeric_code: "044", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert bahamian_dollar.__str__() == 'BSD 10,00.00000'
def test_bahamian_dollar_changed(self):
"""test_cbahamian_dollar_changed."""
bahamian_dollar = BahamianDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
bahamian_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
bahamian_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
bahamian_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
bahamian_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
bahamian_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
bahamian_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
bahamian_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
bahamian_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
bahamian_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
bahamian_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
bahamian_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
bahamian_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
bahamian_dollar.international = True
def test_bahamian_dollar_math_add(self):
"""test_bahamian_dollar_math_add."""
bahamian_dollar_one = BahamianDollar(amount=1)
bahamian_dollar_two = BahamianDollar(amount=2)
bahamian_dollar_three = BahamianDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency BSD and OTHER.'):
_ = bahamian_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.BahamianDollar\'> '
'and <class \'str\'>.')):
_ = bahamian_dollar_one.__add__('1.00')
assert (
bahamian_dollar_one +
bahamian_dollar_two) == bahamian_dollar_three
def test_bahamian_dollar_slots(self):
"""test_bahamian_dollar_slots."""
bahamian_dollar = BahamianDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'BahamianDollar\' '
'object has no attribute \'new_variable\'')):
bahamian_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Belize Dollar representation."""
from multicurrency import BelizeDollar
class TestBelizeDollar:
"""BelizeDollar currency tests."""
def test_belize_dollar(self):
"""test_belize_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
belize_dollar = BelizeDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert belize_dollar.amount == decimal
assert belize_dollar.numeric_code == '084'
assert belize_dollar.alpha_code == 'BZD'
assert belize_dollar.decimal_places == 2
assert belize_dollar.decimal_sign == '.'
assert belize_dollar.grouping_places == 3
assert belize_dollar.grouping_sign == ','
assert not belize_dollar.international
assert belize_dollar.symbol == '$'
assert belize_dollar.symbol_ahead
assert belize_dollar.symbol_separator == ''
assert belize_dollar.localized_symbol == 'BZ$'
assert belize_dollar.convertion == ''
assert belize_dollar.__hash__() == hash(
(belize_dollar.__class__, decimal, 'BZD', '084'))
assert belize_dollar.__repr__() == (
'BelizeDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "BZD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "BZ$", '
'numeric_code: "084", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert belize_dollar.__str__() == '$0.14'
def test_belize_dollar_negative(self):
"""test_belize_dollar_negative."""
amount = -100
belize_dollar = BelizeDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert belize_dollar.numeric_code == '084'
assert belize_dollar.alpha_code == 'BZD'
assert belize_dollar.decimal_places == 2
assert belize_dollar.decimal_sign == '.'
assert belize_dollar.grouping_places == 3
assert belize_dollar.grouping_sign == ','
assert not belize_dollar.international
assert belize_dollar.symbol == '$'
assert belize_dollar.symbol_ahead
assert belize_dollar.symbol_separator == ''
assert belize_dollar.localized_symbol == 'BZ$'
assert belize_dollar.convertion == ''
assert belize_dollar.__hash__() == hash(
(belize_dollar.__class__, decimal, 'BZD', '084'))
assert belize_dollar.__repr__() == (
'BelizeDollar(amount: -100, '
'alpha_code: "BZD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "BZ$", '
'numeric_code: "084", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert belize_dollar.__str__() == '$-100.00'
def test_belize_dollar_custom(self):
"""test_belize_dollar_custom."""
amount = 1000
belize_dollar = BelizeDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert belize_dollar.amount == decimal
assert belize_dollar.numeric_code == '084'
assert belize_dollar.alpha_code == 'BZD'
assert belize_dollar.decimal_places == 5
assert belize_dollar.decimal_sign == ','
assert belize_dollar.grouping_places == 2
assert belize_dollar.grouping_sign == '.'
assert belize_dollar.international
assert belize_dollar.symbol == '$'
assert not belize_dollar.symbol_ahead
assert belize_dollar.symbol_separator == '_'
assert belize_dollar.localized_symbol == 'BZ$'
assert belize_dollar.convertion == ''
assert belize_dollar.__hash__() == hash(
(belize_dollar.__class__, decimal, 'BZD', '084'))
assert belize_dollar.__repr__() == (
'BelizeDollar(amount: 1000, '
'alpha_code: "BZD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "BZ$", '
'numeric_code: "084", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert belize_dollar.__str__() == 'BZD 10,00.00000'
def test_belize_dollar_changed(self):
"""test_cbelize_dollar_changed."""
belize_dollar = BelizeDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
belize_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
belize_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
belize_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
belize_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
belize_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
belize_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
belize_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
belize_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
belize_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
belize_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
belize_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
belize_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
belize_dollar.international = True
def test_belize_dollar_math_add(self):
"""test_belize_dollar_math_add."""
belize_dollar_one = BelizeDollar(amount=1)
belize_dollar_two = BelizeDollar(amount=2)
belize_dollar_three = BelizeDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency BZD and OTHER.'):
_ = belize_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.BelizeDollar\'> '
'and <class \'str\'>.')):
_ = belize_dollar_one.__add__('1.00')
assert (
belize_dollar_one +
belize_dollar_two) == belize_dollar_three
def test_belize_dollar_slots(self):
"""test_belize_dollar_slots."""
belize_dollar = BelizeDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'BelizeDollar\' '
'object has no attribute \'new_variable\'')):
belize_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Canadian Dollar EN representation."""
from multicurrency import CanadianDollarEN
class TestCanadianDollarEN:
"""CanadianDollarEN currency tests."""
def test_canadian_dollar_en(self):
"""test_canadian_dollar_en."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
canadian_dollar_en = CanadianDollarEN(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert canadian_dollar_en.amount == decimal
assert canadian_dollar_en.numeric_code == '124'
assert canadian_dollar_en.alpha_code == 'CAD'
assert canadian_dollar_en.decimal_places == 2
assert canadian_dollar_en.decimal_sign == '.'
assert canadian_dollar_en.grouping_places == 3
assert canadian_dollar_en.grouping_sign == ','
assert not canadian_dollar_en.international
assert canadian_dollar_en.symbol == '$'
assert canadian_dollar_en.symbol_ahead
assert canadian_dollar_en.symbol_separator == ''
assert canadian_dollar_en.localized_symbol == 'CA$'
assert canadian_dollar_en.convertion == ''
assert canadian_dollar_en.__hash__() == hash(
(canadian_dollar_en.__class__, decimal, 'CAD', '124'))
assert canadian_dollar_en.__repr__() == (
'CanadianDollarEN(amount: 0.1428571428571428571428571429, '
'alpha_code: "CAD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "CA$", '
'numeric_code: "124", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert canadian_dollar_en.__str__() == '$0.14'
def test_canadian_dollar_en_negative(self):
"""test_canadian_dollar_en_negative."""
amount = -100
canadian_dollar_en = CanadianDollarEN(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert canadian_dollar_en.numeric_code == '124'
assert canadian_dollar_en.alpha_code == 'CAD'
assert canadian_dollar_en.decimal_places == 2
assert canadian_dollar_en.decimal_sign == '.'
assert canadian_dollar_en.grouping_places == 3
assert canadian_dollar_en.grouping_sign == ','
assert not canadian_dollar_en.international
assert canadian_dollar_en.symbol == '$'
assert canadian_dollar_en.symbol_ahead
assert canadian_dollar_en.symbol_separator == ''
assert canadian_dollar_en.localized_symbol == 'CA$'
assert canadian_dollar_en.convertion == ''
assert canadian_dollar_en.__hash__() == hash(
(canadian_dollar_en.__class__, decimal, 'CAD', '124'))
assert canadian_dollar_en.__repr__() == (
'CanadianDollarEN(amount: -100, '
'alpha_code: "CAD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "CA$", '
'numeric_code: "124", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert canadian_dollar_en.__str__() == '$-100.00'
def test_canadian_dollar_en_custom(self):
"""test_canadian_dollar_en_custom."""
amount = 1000
canadian_dollar_en = CanadianDollarEN(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert canadian_dollar_en.amount == decimal
assert canadian_dollar_en.numeric_code == '124'
assert canadian_dollar_en.alpha_code == 'CAD'
assert canadian_dollar_en.decimal_places == 5
assert canadian_dollar_en.decimal_sign == ','
assert canadian_dollar_en.grouping_places == 2
assert canadian_dollar_en.grouping_sign == '.'
assert canadian_dollar_en.international
assert canadian_dollar_en.symbol == '$'
assert not canadian_dollar_en.symbol_ahead
assert canadian_dollar_en.symbol_separator == '_'
assert canadian_dollar_en.localized_symbol == 'CA$'
assert canadian_dollar_en.convertion == ''
assert canadian_dollar_en.__hash__() == hash(
(canadian_dollar_en.__class__, decimal, 'CAD', '124'))
assert canadian_dollar_en.__repr__() == (
'CanadianDollarEN(amount: 1000, '
'alpha_code: "CAD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "CA$", '
'numeric_code: "124", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert canadian_dollar_en.__str__() == 'CAD 10,00.00000'
def test_canadian_dollar_en_changed(self):
"""test_ccanadian_dollar_en_changed."""
canadian_dollar_en = CanadianDollarEN(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_en.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_en.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_en.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_en.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_en.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_en.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_en.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_en.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_en.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_en.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_en.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_en.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_en.international = True
def test_canadian_dollar_en_math_add(self):
"""test_canadian_dollar_en_math_add."""
canadian_dollar_en_one = CanadianDollarEN(amount=1)
canadian_dollar_en_two = CanadianDollarEN(amount=2)
canadian_dollar_en_three = CanadianDollarEN(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency CAD and OTHER.'):
_ = canadian_dollar_en_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.CanadianDollarEN\'> '
'and <class \'str\'>.')):
_ = canadian_dollar_en_one.__add__('1.00')
assert (
canadian_dollar_en_one +
canadian_dollar_en_two) == canadian_dollar_en_three
def test_canadian_dollar_en_slots(self):
"""test_canadian_dollar_en_slots."""
canadian_dollar_en = CanadianDollarEN(amount=1000)
with raises(
AttributeError,
match=(
'\'CanadianDollarEN\' '
'object has no attribute \'new_variable\'')):
canadian_dollar_en.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Canadian Dollar FR representation."""
from multicurrency import CanadianDollarFR
class TestCanadianDollarFR:
"""CanadianDollarFR currency tests."""
def test_canadian_dollar_fr(self):
"""test_canadian_dollar_fr."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
canadian_dollar_fr = CanadianDollarFR(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert canadian_dollar_fr.amount == decimal
assert canadian_dollar_fr.numeric_code == '124'
assert canadian_dollar_fr.alpha_code == 'CAD'
assert canadian_dollar_fr.decimal_places == 2
assert canadian_dollar_fr.decimal_sign == ','
assert canadian_dollar_fr.grouping_places == 3
assert canadian_dollar_fr.grouping_sign == '\u202F'
assert not canadian_dollar_fr.international
assert canadian_dollar_fr.symbol == '$'
assert not canadian_dollar_fr.symbol_ahead
assert canadian_dollar_fr.symbol_separator == '\u00A0'
assert canadian_dollar_fr.localized_symbol == 'CA$'
assert canadian_dollar_fr.convertion == ''
assert canadian_dollar_fr.__hash__() == hash(
(canadian_dollar_fr.__class__, decimal, 'CAD', '124'))
assert canadian_dollar_fr.__repr__() == (
'CanadianDollarFR(amount: 0.1428571428571428571428571429, '
'alpha_code: "CAD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "\u00A0", '
'localized_symbol: "CA$", '
'numeric_code: "124", '
'decimal_places: "2", '
'decimal_sign: ",", '
'grouping_places: "3", '
'grouping_sign: "\u202F", '
'convertion: "", '
'international: False)')
assert canadian_dollar_fr.__str__() == '0,14 $'
def test_canadian_dollar_fr_negative(self):
"""test_canadian_dollar_fr_negative."""
amount = -100
canadian_dollar_fr = CanadianDollarFR(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert canadian_dollar_fr.numeric_code == '124'
assert canadian_dollar_fr.alpha_code == 'CAD'
assert canadian_dollar_fr.decimal_places == 2
assert canadian_dollar_fr.decimal_sign == ','
assert canadian_dollar_fr.grouping_places == 3
assert canadian_dollar_fr.grouping_sign == '\u202F'
assert not canadian_dollar_fr.international
assert canadian_dollar_fr.symbol == '$'
assert not canadian_dollar_fr.symbol_ahead
assert canadian_dollar_fr.symbol_separator == '\u00A0'
assert canadian_dollar_fr.localized_symbol == 'CA$'
assert canadian_dollar_fr.convertion == ''
assert canadian_dollar_fr.__hash__() == hash(
(canadian_dollar_fr.__class__, decimal, 'CAD', '124'))
assert canadian_dollar_fr.__repr__() == (
'CanadianDollarFR(amount: -100, '
'alpha_code: "CAD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "\u00A0", '
'localized_symbol: "CA$", '
'numeric_code: "124", '
'decimal_places: "2", '
'decimal_sign: ",", '
'grouping_places: "3", '
'grouping_sign: "\u202F", '
'convertion: "", '
'international: False)')
assert canadian_dollar_fr.__str__() == '-100,00 $'
def test_canadian_dollar_fr_custom(self):
"""test_canadian_dollar_fr_custom."""
amount = 1000
canadian_dollar_fr = CanadianDollarFR(
amount=amount,
decimal_places=5,
decimal_sign='\u202F',
grouping_places=2,
grouping_sign=',',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert canadian_dollar_fr.amount == decimal
assert canadian_dollar_fr.numeric_code == '124'
assert canadian_dollar_fr.alpha_code == 'CAD'
assert canadian_dollar_fr.decimal_places == 5
assert canadian_dollar_fr.decimal_sign == '\u202F'
assert canadian_dollar_fr.grouping_places == 2
assert canadian_dollar_fr.grouping_sign == ','
assert canadian_dollar_fr.international
assert canadian_dollar_fr.symbol == '$'
assert not canadian_dollar_fr.symbol_ahead
assert canadian_dollar_fr.symbol_separator == '_'
assert canadian_dollar_fr.localized_symbol == 'CA$'
assert canadian_dollar_fr.convertion == ''
assert canadian_dollar_fr.__hash__() == hash(
(canadian_dollar_fr.__class__, decimal, 'CAD', '124'))
assert canadian_dollar_fr.__repr__() == (
'CanadianDollarFR(amount: 1000, '
'alpha_code: "CAD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "CA$", '
'numeric_code: "124", '
'decimal_places: "5", '
'decimal_sign: "\u202F", '
'grouping_places: "2", '
'grouping_sign: ",", '
'convertion: "", '
'international: True)')
assert canadian_dollar_fr.__str__() == 'CAD 10,00.00000'
def test_canadian_dollar_fr_changed(self):
"""test_ccanadian_dollar_fr_changed."""
canadian_dollar_fr = CanadianDollarFR(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_fr.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_fr.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_fr.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_fr.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_fr.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_fr.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_fr.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_fr.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_fr.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_fr.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_fr.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_fr.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
canadian_dollar_fr.international = True
def test_canadian_dollar_fr_math_add(self):
"""test_canadian_dollar_fr_math_add."""
canadian_dollar_fr_one = CanadianDollarFR(amount=1)
canadian_dollar_fr_two = CanadianDollarFR(amount=2)
canadian_dollar_fr_three = CanadianDollarFR(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency CAD and OTHER.'):
_ = canadian_dollar_fr_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.CanadianDollarFR\'> '
'and <class \'str\'>.')):
_ = canadian_dollar_fr_one.__add__('1.00')
assert (
canadian_dollar_fr_one +
canadian_dollar_fr_two) == canadian_dollar_fr_three
def test_canadian_dollar_fr_slots(self):
"""test_canadian_dollar_fr_slots."""
canadian_dollar_fr = CanadianDollarFR(amount=1000)
with raises(
AttributeError,
match=(
'\'CanadianDollarFR\' '
'object has no attribute \'new_variable\'')):
canadian_dollar_fr.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Fiji Dollar representation."""
from multicurrency import FijiDollar
class TestFijiDollar:
"""FijiDollar currency tests."""
def test_fiji_dollar(self):
"""test_fiji_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
fiji_dollar = FijiDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert fiji_dollar.amount == decimal
assert fiji_dollar.numeric_code == '242'
assert fiji_dollar.alpha_code == 'FJD'
assert fiji_dollar.decimal_places == 2
assert fiji_dollar.decimal_sign == '.'
assert fiji_dollar.grouping_places == 3
assert fiji_dollar.grouping_sign == ','
assert not fiji_dollar.international
assert fiji_dollar.symbol == '$'
assert fiji_dollar.symbol_ahead
assert fiji_dollar.symbol_separator == ''
assert fiji_dollar.localized_symbol == 'FJ$'
assert fiji_dollar.convertion == ''
assert fiji_dollar.__hash__() == hash(
(fiji_dollar.__class__, decimal, 'FJD', '242'))
assert fiji_dollar.__repr__() == (
'FijiDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "FJD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "FJ$", '
'numeric_code: "242", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert fiji_dollar.__str__() == '$0.14'
def test_fiji_dollar_negative(self):
"""test_fiji_dollar_negative."""
amount = -100
fiji_dollar = FijiDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert fiji_dollar.numeric_code == '242'
assert fiji_dollar.alpha_code == 'FJD'
assert fiji_dollar.decimal_places == 2
assert fiji_dollar.decimal_sign == '.'
assert fiji_dollar.grouping_places == 3
assert fiji_dollar.grouping_sign == ','
assert not fiji_dollar.international
assert fiji_dollar.symbol == '$'
assert fiji_dollar.symbol_ahead
assert fiji_dollar.symbol_separator == ''
assert fiji_dollar.localized_symbol == 'FJ$'
assert fiji_dollar.convertion == ''
assert fiji_dollar.__hash__() == hash(
(fiji_dollar.__class__, decimal, 'FJD', '242'))
assert fiji_dollar.__repr__() == (
'FijiDollar(amount: -100, '
'alpha_code: "FJD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "FJ$", '
'numeric_code: "242", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert fiji_dollar.__str__() == '$-100.00'
def test_fiji_dollar_custom(self):
"""test_fiji_dollar_custom."""
amount = 1000
fiji_dollar = FijiDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert fiji_dollar.amount == decimal
assert fiji_dollar.numeric_code == '242'
assert fiji_dollar.alpha_code == 'FJD'
assert fiji_dollar.decimal_places == 5
assert fiji_dollar.decimal_sign == ','
assert fiji_dollar.grouping_places == 2
assert fiji_dollar.grouping_sign == '.'
assert fiji_dollar.international
assert fiji_dollar.symbol == '$'
assert not fiji_dollar.symbol_ahead
assert fiji_dollar.symbol_separator == '_'
assert fiji_dollar.localized_symbol == 'FJ$'
assert fiji_dollar.convertion == ''
assert fiji_dollar.__hash__() == hash(
(fiji_dollar.__class__, decimal, 'FJD', '242'))
assert fiji_dollar.__repr__() == (
'FijiDollar(amount: 1000, '
'alpha_code: "FJD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "FJ$", '
'numeric_code: "242", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert fiji_dollar.__str__() == 'FJD 10,00.00000'
def test_fiji_dollar_changed(self):
"""test_cfiji_dollar_changed."""
fiji_dollar = FijiDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
fiji_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
fiji_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
fiji_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
fiji_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
fiji_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
fiji_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
fiji_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
fiji_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
fiji_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
fiji_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
fiji_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
fiji_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
fiji_dollar.international = True
def test_fiji_dollar_math_add(self):
"""test_fiji_dollar_math_add."""
fiji_dollar_one = FijiDollar(amount=1)
fiji_dollar_two = FijiDollar(amount=2)
fiji_dollar_three = FijiDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency FJD and OTHER.'):
_ = fiji_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.FijiDollar\'> '
'and <class \'str\'>.')):
_ = fiji_dollar_one.__add__('1.00')
assert (
fiji_dollar_one +
fiji_dollar_two) == fiji_dollar_three
def test_fiji_dollar_slots(self):
"""test_fiji_dollar_slots."""
fiji_dollar = FijiDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'FijiDollar\' '
'object has no attribute \'new_variable\'')):
fiji_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Guyana Dollar representation."""
from multicurrency import GuyanaDollar
class TestGuyanaDollar:
"""GuyanaDollar currency tests."""
def test_guyana_dollar(self):
"""test_guyana_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
guyana_dollar = GuyanaDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert guyana_dollar.amount == decimal
assert guyana_dollar.numeric_code == '328'
assert guyana_dollar.alpha_code == 'GYD'
assert guyana_dollar.decimal_places == 2
assert guyana_dollar.decimal_sign == '.'
assert guyana_dollar.grouping_places == 3
assert guyana_dollar.grouping_sign == ','
assert not guyana_dollar.international
assert guyana_dollar.symbol == '$'
assert guyana_dollar.symbol_ahead
assert guyana_dollar.symbol_separator == ''
assert guyana_dollar.localized_symbol == 'GY$'
assert guyana_dollar.convertion == ''
assert guyana_dollar.__hash__() == hash(
(guyana_dollar.__class__, decimal, 'GYD', '328'))
assert guyana_dollar.__repr__() == (
'GuyanaDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "GYD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "GY$", '
'numeric_code: "328", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert guyana_dollar.__str__() == '$0.14'
def test_guyana_dollar_negative(self):
"""test_guyana_dollar_negative."""
amount = -100
guyana_dollar = GuyanaDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert guyana_dollar.numeric_code == '328'
assert guyana_dollar.alpha_code == 'GYD'
assert guyana_dollar.decimal_places == 2
assert guyana_dollar.decimal_sign == '.'
assert guyana_dollar.grouping_places == 3
assert guyana_dollar.grouping_sign == ','
assert not guyana_dollar.international
assert guyana_dollar.symbol == '$'
assert guyana_dollar.symbol_ahead
assert guyana_dollar.symbol_separator == ''
assert guyana_dollar.localized_symbol == 'GY$'
assert guyana_dollar.convertion == ''
assert guyana_dollar.__hash__() == hash(
(guyana_dollar.__class__, decimal, 'GYD', '328'))
assert guyana_dollar.__repr__() == (
'GuyanaDollar(amount: -100, '
'alpha_code: "GYD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "GY$", '
'numeric_code: "328", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert guyana_dollar.__str__() == '$-100.00'
def test_guyana_dollar_custom(self):
"""test_guyana_dollar_custom."""
amount = 1000
guyana_dollar = GuyanaDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert guyana_dollar.amount == decimal
assert guyana_dollar.numeric_code == '328'
assert guyana_dollar.alpha_code == 'GYD'
assert guyana_dollar.decimal_places == 5
assert guyana_dollar.decimal_sign == ','
assert guyana_dollar.grouping_places == 2
assert guyana_dollar.grouping_sign == '.'
assert guyana_dollar.international
assert guyana_dollar.symbol == '$'
assert not guyana_dollar.symbol_ahead
assert guyana_dollar.symbol_separator == '_'
assert guyana_dollar.localized_symbol == 'GY$'
assert guyana_dollar.convertion == ''
assert guyana_dollar.__hash__() == hash(
(guyana_dollar.__class__, decimal, 'GYD', '328'))
assert guyana_dollar.__repr__() == (
'GuyanaDollar(amount: 1000, '
'alpha_code: "GYD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "GY$", '
'numeric_code: "328", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert guyana_dollar.__str__() == 'GYD 10,00.00000'
def test_guyana_dollar_changed(self):
"""test_cguyana_dollar_changed."""
guyana_dollar = GuyanaDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
guyana_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
guyana_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
guyana_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
guyana_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
guyana_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
guyana_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
guyana_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
guyana_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
guyana_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
guyana_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
guyana_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
guyana_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
guyana_dollar.international = True
def test_guyana_dollar_math_add(self):
"""test_guyana_dollar_math_add."""
guyana_dollar_one = GuyanaDollar(amount=1)
guyana_dollar_two = GuyanaDollar(amount=2)
guyana_dollar_three = GuyanaDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency GYD and OTHER.'):
_ = guyana_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.GuyanaDollar\'> '
'and <class \'str\'>.')):
_ = guyana_dollar_one.__add__('1.00')
assert (
guyana_dollar_one +
guyana_dollar_two) == guyana_dollar_three
def test_guyana_dollar_slots(self):
"""test_guyana_dollar_slots."""
guyana_dollar = GuyanaDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'GuyanaDollar\' '
'object has no attribute \'new_variable\'')):
guyana_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Hong Kong Dollar representation."""
from multicurrency import HongKongDollar
class TestHongKongDollar:
"""HongKongDollar currency tests."""
def test_hong_kong_dollar(self):
"""test_hong_kong_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
hong_kong_dollar = HongKongDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert hong_kong_dollar.amount == decimal
assert hong_kong_dollar.numeric_code == '344'
assert hong_kong_dollar.alpha_code == 'HKD'
assert hong_kong_dollar.decimal_places == 2
assert hong_kong_dollar.decimal_sign == '.'
assert hong_kong_dollar.grouping_places == 3
assert hong_kong_dollar.grouping_sign == ','
assert not hong_kong_dollar.international
assert hong_kong_dollar.symbol == '$'
assert hong_kong_dollar.symbol_ahead
assert hong_kong_dollar.symbol_separator == ''
assert hong_kong_dollar.localized_symbol == 'HK$'
assert hong_kong_dollar.convertion == ''
assert hong_kong_dollar.__hash__() == hash(
(hong_kong_dollar.__class__, decimal, 'HKD', '344'))
assert hong_kong_dollar.__repr__() == (
'HongKongDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "HKD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "HK$", '
'numeric_code: "344", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert hong_kong_dollar.__str__() == '$0.14'
def test_hong_kong_dollar_negative(self):
"""test_hong_kong_dollar_negative."""
amount = -100
hong_kong_dollar = HongKongDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert hong_kong_dollar.numeric_code == '344'
assert hong_kong_dollar.alpha_code == 'HKD'
assert hong_kong_dollar.decimal_places == 2
assert hong_kong_dollar.decimal_sign == '.'
assert hong_kong_dollar.grouping_places == 3
assert hong_kong_dollar.grouping_sign == ','
assert not hong_kong_dollar.international
assert hong_kong_dollar.symbol == '$'
assert hong_kong_dollar.symbol_ahead
assert hong_kong_dollar.symbol_separator == ''
assert hong_kong_dollar.localized_symbol == 'HK$'
assert hong_kong_dollar.convertion == ''
assert hong_kong_dollar.__hash__() == hash(
(hong_kong_dollar.__class__, decimal, 'HKD', '344'))
assert hong_kong_dollar.__repr__() == (
'HongKongDollar(amount: -100, '
'alpha_code: "HKD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "HK$", '
'numeric_code: "344", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert hong_kong_dollar.__str__() == '$-100.00'
def test_hong_kong_dollar_custom(self):
"""test_hong_kong_dollar_custom."""
amount = 1000
hong_kong_dollar = HongKongDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert hong_kong_dollar.amount == decimal
assert hong_kong_dollar.numeric_code == '344'
assert hong_kong_dollar.alpha_code == 'HKD'
assert hong_kong_dollar.decimal_places == 5
assert hong_kong_dollar.decimal_sign == ','
assert hong_kong_dollar.grouping_places == 2
assert hong_kong_dollar.grouping_sign == '.'
assert hong_kong_dollar.international
assert hong_kong_dollar.symbol == '$'
assert not hong_kong_dollar.symbol_ahead
assert hong_kong_dollar.symbol_separator == '_'
assert hong_kong_dollar.localized_symbol == 'HK$'
assert hong_kong_dollar.convertion == ''
assert hong_kong_dollar.__hash__() == hash(
(hong_kong_dollar.__class__, decimal, 'HKD', '344'))
assert hong_kong_dollar.__repr__() == (
'HongKongDollar(amount: 1000, '
'alpha_code: "HKD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "HK$", '
'numeric_code: "344", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert hong_kong_dollar.__str__() == 'HKD 10,00.00000'
def test_hong_kong_dollar_changed(self):
"""test_chong_kong_dollar_changed."""
hong_kong_dollar = HongKongDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
hong_kong_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
hong_kong_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
hong_kong_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
hong_kong_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
hong_kong_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
hong_kong_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
hong_kong_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
hong_kong_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
hong_kong_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
hong_kong_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
hong_kong_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
hong_kong_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
hong_kong_dollar.international = True
def test_hong_kong_dollar_math_add(self):
"""test_hong_kong_dollar_math_add."""
hong_kong_dollar_one = HongKongDollar(amount=1)
hong_kong_dollar_two = HongKongDollar(amount=2)
hong_kong_dollar_three = HongKongDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency HKD and OTHER.'):
_ = hong_kong_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.HongKongDollar\'> '
'and <class \'str\'>.')):
_ = hong_kong_dollar_one.__add__('1.00')
assert (
hong_kong_dollar_one +
hong_kong_dollar_two) == hong_kong_dollar_three
def test_hong_kong_dollar_slots(self):
"""test_hong_kong_dollar_slots."""
hong_kong_dollar = HongKongDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'HongKongDollar\' '
'object has no attribute \'new_variable\'')):
hong_kong_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Jamaican Dollar representation."""
from multicurrency import JamaicanDollar
class TestJamaicanDollar:
"""JamaicanDollar currency tests."""
def test_jamaican_dollar(self):
"""test_jamaican_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
jamaican_dollar = JamaicanDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert jamaican_dollar.amount == decimal
assert jamaican_dollar.numeric_code == '388'
assert jamaican_dollar.alpha_code == 'JMD'
assert jamaican_dollar.decimal_places == 2
assert jamaican_dollar.decimal_sign == '.'
assert jamaican_dollar.grouping_places == 3
assert jamaican_dollar.grouping_sign == ','
assert not jamaican_dollar.international
assert jamaican_dollar.symbol == '$'
assert jamaican_dollar.symbol_ahead
assert jamaican_dollar.symbol_separator == ''
assert jamaican_dollar.localized_symbol == 'JM$'
assert jamaican_dollar.convertion == ''
assert jamaican_dollar.__hash__() == hash(
(jamaican_dollar.__class__, decimal, 'JMD', '388'))
assert jamaican_dollar.__repr__() == (
'JamaicanDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "JMD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "JM$", '
'numeric_code: "388", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert jamaican_dollar.__str__() == '$0.14'
def test_jamaican_dollar_negative(self):
"""test_jamaican_dollar_negative."""
amount = -100
jamaican_dollar = JamaicanDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert jamaican_dollar.numeric_code == '388'
assert jamaican_dollar.alpha_code == 'JMD'
assert jamaican_dollar.decimal_places == 2
assert jamaican_dollar.decimal_sign == '.'
assert jamaican_dollar.grouping_places == 3
assert jamaican_dollar.grouping_sign == ','
assert not jamaican_dollar.international
assert jamaican_dollar.symbol == '$'
assert jamaican_dollar.symbol_ahead
assert jamaican_dollar.symbol_separator == ''
assert jamaican_dollar.localized_symbol == 'JM$'
assert jamaican_dollar.convertion == ''
assert jamaican_dollar.__hash__() == hash(
(jamaican_dollar.__class__, decimal, 'JMD', '388'))
assert jamaican_dollar.__repr__() == (
'JamaicanDollar(amount: -100, '
'alpha_code: "JMD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "JM$", '
'numeric_code: "388", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert jamaican_dollar.__str__() == '$-100.00'
def test_jamaican_dollar_custom(self):
"""test_jamaican_dollar_custom."""
amount = 1000
jamaican_dollar = JamaicanDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert jamaican_dollar.amount == decimal
assert jamaican_dollar.numeric_code == '388'
assert jamaican_dollar.alpha_code == 'JMD'
assert jamaican_dollar.decimal_places == 5
assert jamaican_dollar.decimal_sign == ','
assert jamaican_dollar.grouping_places == 2
assert jamaican_dollar.grouping_sign == '.'
assert jamaican_dollar.international
assert jamaican_dollar.symbol == '$'
assert not jamaican_dollar.symbol_ahead
assert jamaican_dollar.symbol_separator == '_'
assert jamaican_dollar.localized_symbol == 'JM$'
assert jamaican_dollar.convertion == ''
assert jamaican_dollar.__hash__() == hash(
(jamaican_dollar.__class__, decimal, 'JMD', '388'))
assert jamaican_dollar.__repr__() == (
'JamaicanDollar(amount: 1000, '
'alpha_code: "JMD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "JM$", '
'numeric_code: "388", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert jamaican_dollar.__str__() == 'JMD 10,00.00000'
def test_jamaican_dollar_changed(self):
"""test_cjamaican_dollar_changed."""
jamaican_dollar = JamaicanDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
jamaican_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
jamaican_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
jamaican_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
jamaican_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
jamaican_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
jamaican_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
jamaican_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
jamaican_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
jamaican_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
jamaican_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
jamaican_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
jamaican_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
jamaican_dollar.international = True
def test_jamaican_dollar_math_add(self):
"""test_jamaican_dollar_math_add."""
jamaican_dollar_one = JamaicanDollar(amount=1)
jamaican_dollar_two = JamaicanDollar(amount=2)
jamaican_dollar_three = JamaicanDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency JMD and OTHER.'):
_ = jamaican_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.JamaicanDollar\'> '
'and <class \'str\'>.')):
_ = jamaican_dollar_one.__add__('1.00')
assert (
jamaican_dollar_one +
jamaican_dollar_two) == jamaican_dollar_three
def test_jamaican_dollar_slots(self):
"""test_jamaican_dollar_slots."""
jamaican_dollar = JamaicanDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'JamaicanDollar\' '
'object has no attribute \'new_variable\'')):
jamaican_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Cayman Islands Dollar representation."""
from multicurrency import CaymanIslandsDollar
class TestCaymanIslandsDollar:
"""CaymanIslandsDollar currency tests."""
def test_cayman_islands_dollar(self):
"""test_cayman_islands_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
cayman_islands_dollar = CaymanIslandsDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert cayman_islands_dollar.amount == decimal
assert cayman_islands_dollar.numeric_code == '136'
assert cayman_islands_dollar.alpha_code == 'KYD'
assert cayman_islands_dollar.decimal_places == 2
assert cayman_islands_dollar.decimal_sign == '.'
assert cayman_islands_dollar.grouping_places == 3
assert cayman_islands_dollar.grouping_sign == ','
assert not cayman_islands_dollar.international
assert cayman_islands_dollar.symbol == '$'
assert cayman_islands_dollar.symbol_ahead
assert cayman_islands_dollar.symbol_separator == ''
assert cayman_islands_dollar.localized_symbol == 'KY$'
assert cayman_islands_dollar.convertion == ''
assert cayman_islands_dollar.__hash__() == hash(
(cayman_islands_dollar.__class__, decimal, 'KYD', '136'))
assert cayman_islands_dollar.__repr__() == (
'CaymanIslandsDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "KYD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "KY$", '
'numeric_code: "136", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert cayman_islands_dollar.__str__() == '$0.14'
def test_cayman_islands_dollar_negative(self):
"""test_cayman_islands_dollar_negative."""
amount = -100
cayman_islands_dollar = CaymanIslandsDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert cayman_islands_dollar.numeric_code == '136'
assert cayman_islands_dollar.alpha_code == 'KYD'
assert cayman_islands_dollar.decimal_places == 2
assert cayman_islands_dollar.decimal_sign == '.'
assert cayman_islands_dollar.grouping_places == 3
assert cayman_islands_dollar.grouping_sign == ','
assert not cayman_islands_dollar.international
assert cayman_islands_dollar.symbol == '$'
assert cayman_islands_dollar.symbol_ahead
assert cayman_islands_dollar.symbol_separator == ''
assert cayman_islands_dollar.localized_symbol == 'KY$'
assert cayman_islands_dollar.convertion == ''
assert cayman_islands_dollar.__hash__() == hash(
(cayman_islands_dollar.__class__, decimal, 'KYD', '136'))
assert cayman_islands_dollar.__repr__() == (
'CaymanIslandsDollar(amount: -100, '
'alpha_code: "KYD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "KY$", '
'numeric_code: "136", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert cayman_islands_dollar.__str__() == '$-100.00'
def test_cayman_islands_dollar_custom(self):
"""test_cayman_islands_dollar_custom."""
amount = 1000
cayman_islands_dollar = CaymanIslandsDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert cayman_islands_dollar.amount == decimal
assert cayman_islands_dollar.numeric_code == '136'
assert cayman_islands_dollar.alpha_code == 'KYD'
assert cayman_islands_dollar.decimal_places == 5
assert cayman_islands_dollar.decimal_sign == ','
assert cayman_islands_dollar.grouping_places == 2
assert cayman_islands_dollar.grouping_sign == '.'
assert cayman_islands_dollar.international
assert cayman_islands_dollar.symbol == '$'
assert not cayman_islands_dollar.symbol_ahead
assert cayman_islands_dollar.symbol_separator == '_'
assert cayman_islands_dollar.localized_symbol == 'KY$'
assert cayman_islands_dollar.convertion == ''
assert cayman_islands_dollar.__hash__() == hash(
(cayman_islands_dollar.__class__, decimal, 'KYD', '136'))
assert cayman_islands_dollar.__repr__() == (
'CaymanIslandsDollar(amount: 1000, '
'alpha_code: "KYD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "KY$", '
'numeric_code: "136", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert cayman_islands_dollar.__str__() == 'KYD 10,00.00000'
def test_cayman_islands_dollar_changed(self):
"""test_ccayman_islands_dollar_changed."""
cayman_islands_dollar = CaymanIslandsDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
cayman_islands_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
cayman_islands_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
cayman_islands_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
cayman_islands_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
cayman_islands_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
cayman_islands_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
cayman_islands_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
cayman_islands_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
cayman_islands_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
cayman_islands_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
cayman_islands_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
cayman_islands_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
cayman_islands_dollar.international = True
def test_cayman_islands_dollar_math_add(self):
"""test_cayman_islands_dollar_math_add."""
cayman_islands_dollar_one = CaymanIslandsDollar(amount=1)
cayman_islands_dollar_two = CaymanIslandsDollar(amount=2)
cayman_islands_dollar_three = CaymanIslandsDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency KYD and OTHER.'):
_ = cayman_islands_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.CaymanIslandsDollar\'> '
'and <class \'str\'>.')):
_ = cayman_islands_dollar_one.__add__('1.00')
assert (
cayman_islands_dollar_one +
cayman_islands_dollar_two) == cayman_islands_dollar_three
def test_cayman_islands_dollar_slots(self):
"""test_cayman_islands_dollar_slots."""
cayman_islands_dollar = CaymanIslandsDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'CaymanIslandsDollar\' '
'object has no attribute \'new_variable\'')):
cayman_islands_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Liberian Dollar representation."""
from multicurrency import LiberianDollar
class TestLiberianDollar:
"""LiberianDollar currency tests."""
def test_liberian_dollar(self):
"""test_liberian_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
liberian_dollar = LiberianDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert liberian_dollar.amount == decimal
assert liberian_dollar.numeric_code == '430'
assert liberian_dollar.alpha_code == 'LRD'
assert liberian_dollar.decimal_places == 2
assert liberian_dollar.decimal_sign == '.'
assert liberian_dollar.grouping_places == 3
assert liberian_dollar.grouping_sign == ','
assert not liberian_dollar.international
assert liberian_dollar.symbol == '$'
assert liberian_dollar.symbol_ahead
assert liberian_dollar.symbol_separator == ''
assert liberian_dollar.localized_symbol == 'LR$'
assert liberian_dollar.convertion == ''
assert liberian_dollar.__hash__() == hash(
(liberian_dollar.__class__, decimal, 'LRD', '430'))
assert liberian_dollar.__repr__() == (
'LiberianDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "LRD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "LR$", '
'numeric_code: "430", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert liberian_dollar.__str__() == '$0.14'
def test_liberian_dollar_negative(self):
"""test_liberian_dollar_negative."""
amount = -100
liberian_dollar = LiberianDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert liberian_dollar.numeric_code == '430'
assert liberian_dollar.alpha_code == 'LRD'
assert liberian_dollar.decimal_places == 2
assert liberian_dollar.decimal_sign == '.'
assert liberian_dollar.grouping_places == 3
assert liberian_dollar.grouping_sign == ','
assert not liberian_dollar.international
assert liberian_dollar.symbol == '$'
assert liberian_dollar.symbol_ahead
assert liberian_dollar.symbol_separator == ''
assert liberian_dollar.localized_symbol == 'LR$'
assert liberian_dollar.convertion == ''
assert liberian_dollar.__hash__() == hash(
(liberian_dollar.__class__, decimal, 'LRD', '430'))
assert liberian_dollar.__repr__() == (
'LiberianDollar(amount: -100, '
'alpha_code: "LRD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "LR$", '
'numeric_code: "430", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert liberian_dollar.__str__() == '$-100.00'
def test_liberian_dollar_custom(self):
"""test_liberian_dollar_custom."""
amount = 1000
liberian_dollar = LiberianDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert liberian_dollar.amount == decimal
assert liberian_dollar.numeric_code == '430'
assert liberian_dollar.alpha_code == 'LRD'
assert liberian_dollar.decimal_places == 5
assert liberian_dollar.decimal_sign == ','
assert liberian_dollar.grouping_places == 2
assert liberian_dollar.grouping_sign == '.'
assert liberian_dollar.international
assert liberian_dollar.symbol == '$'
assert not liberian_dollar.symbol_ahead
assert liberian_dollar.symbol_separator == '_'
assert liberian_dollar.localized_symbol == 'LR$'
assert liberian_dollar.convertion == ''
assert liberian_dollar.__hash__() == hash(
(liberian_dollar.__class__, decimal, 'LRD', '430'))
assert liberian_dollar.__repr__() == (
'LiberianDollar(amount: 1000, '
'alpha_code: "LRD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "LR$", '
'numeric_code: "430", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert liberian_dollar.__str__() == 'LRD 10,00.00000'
def test_liberian_dollar_changed(self):
"""test_cliberian_dollar_changed."""
liberian_dollar = LiberianDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
liberian_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
liberian_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
liberian_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
liberian_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
liberian_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
liberian_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
liberian_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
liberian_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
liberian_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
liberian_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
liberian_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
liberian_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
liberian_dollar.international = True
def test_liberian_dollar_math_add(self):
"""test_liberian_dollar_math_add."""
liberian_dollar_one = LiberianDollar(amount=1)
liberian_dollar_two = LiberianDollar(amount=2)
liberian_dollar_three = LiberianDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency LRD and OTHER.'):
_ = liberian_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.LiberianDollar\'> '
'and <class \'str\'>.')):
_ = liberian_dollar_one.__add__('1.00')
assert (
liberian_dollar_one +
liberian_dollar_two) == liberian_dollar_three
def test_liberian_dollar_slots(self):
"""test_liberian_dollar_slots."""
liberian_dollar = LiberianDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'LiberianDollar\' '
'object has no attribute \'new_variable\'')):
liberian_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Namibia Dollar representation."""
from multicurrency import NamibiaDollar
class TestNamibiaDollar:
"""NamibiaDollar currency tests."""
def test_namibia_dollar(self):
"""test_namibia_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
namibia_dollar = NamibiaDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert namibia_dollar.amount == decimal
assert namibia_dollar.numeric_code == '516'
assert namibia_dollar.alpha_code == 'NAD'
assert namibia_dollar.decimal_places == 2
assert namibia_dollar.decimal_sign == '.'
assert namibia_dollar.grouping_places == 3
assert namibia_dollar.grouping_sign == ','
assert not namibia_dollar.international
assert namibia_dollar.symbol == '$'
assert namibia_dollar.symbol_ahead
assert namibia_dollar.symbol_separator == ''
assert namibia_dollar.localized_symbol == 'NA$'
assert namibia_dollar.convertion == ''
assert namibia_dollar.__hash__() == hash(
(namibia_dollar.__class__, decimal, 'NAD', '516'))
assert namibia_dollar.__repr__() == (
'NamibiaDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "NAD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "NA$", '
'numeric_code: "516", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert namibia_dollar.__str__() == '$0.14'
def test_namibia_dollar_negative(self):
"""test_namibia_dollar_negative."""
amount = -100
namibia_dollar = NamibiaDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert namibia_dollar.numeric_code == '516'
assert namibia_dollar.alpha_code == 'NAD'
assert namibia_dollar.decimal_places == 2
assert namibia_dollar.decimal_sign == '.'
assert namibia_dollar.grouping_places == 3
assert namibia_dollar.grouping_sign == ','
assert not namibia_dollar.international
assert namibia_dollar.symbol == '$'
assert namibia_dollar.symbol_ahead
assert namibia_dollar.symbol_separator == ''
assert namibia_dollar.localized_symbol == 'NA$'
assert namibia_dollar.convertion == ''
assert namibia_dollar.__hash__() == hash(
(namibia_dollar.__class__, decimal, 'NAD', '516'))
assert namibia_dollar.__repr__() == (
'NamibiaDollar(amount: -100, '
'alpha_code: "NAD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "NA$", '
'numeric_code: "516", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert namibia_dollar.__str__() == '$-100.00'
def test_namibia_dollar_custom(self):
"""test_namibia_dollar_custom."""
amount = 1000
namibia_dollar = NamibiaDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert namibia_dollar.amount == decimal
assert namibia_dollar.numeric_code == '516'
assert namibia_dollar.alpha_code == 'NAD'
assert namibia_dollar.decimal_places == 5
assert namibia_dollar.decimal_sign == ','
assert namibia_dollar.grouping_places == 2
assert namibia_dollar.grouping_sign == '.'
assert namibia_dollar.international
assert namibia_dollar.symbol == '$'
assert not namibia_dollar.symbol_ahead
assert namibia_dollar.symbol_separator == '_'
assert namibia_dollar.localized_symbol == 'NA$'
assert namibia_dollar.convertion == ''
assert namibia_dollar.__hash__() == hash(
(namibia_dollar.__class__, decimal, 'NAD', '516'))
assert namibia_dollar.__repr__() == (
'NamibiaDollar(amount: 1000, '
'alpha_code: "NAD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "NA$", '
'numeric_code: "516", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert namibia_dollar.__str__() == 'NAD 10,00.00000'
def test_namibia_dollar_changed(self):
"""test_cnamibia_dollar_changed."""
namibia_dollar = NamibiaDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
namibia_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
namibia_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
namibia_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
namibia_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
namibia_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
namibia_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
namibia_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
namibia_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
namibia_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
namibia_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
namibia_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
namibia_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
namibia_dollar.international = True
def test_namibia_dollar_math_add(self):
"""test_namibia_dollar_math_add."""
namibia_dollar_one = NamibiaDollar(amount=1)
namibia_dollar_two = NamibiaDollar(amount=2)
namibia_dollar_three = NamibiaDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency NAD and OTHER.'):
_ = namibia_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.NamibiaDollar\'> '
'and <class \'str\'>.')):
_ = namibia_dollar_one.__add__('1.00')
assert (
namibia_dollar_one +
namibia_dollar_two) == namibia_dollar_three
def test_namibia_dollar_slots(self):
"""test_namibia_dollar_slots."""
namibia_dollar = NamibiaDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'NamibiaDollar\' '
'object has no attribute \'new_variable\'')):
namibia_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the New Zealand Dollar representation."""
from multicurrency import NewZealandDollar
class TestNewZealandDollar:
"""NewZealandDollar currency tests."""
def test_new_zealand_dollar(self):
"""test_new_zealand_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
new_zealand_dollar = NewZealandDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert new_zealand_dollar.amount == decimal
assert new_zealand_dollar.numeric_code == '554'
assert new_zealand_dollar.alpha_code == 'NZD'
assert new_zealand_dollar.decimal_places == 2
assert new_zealand_dollar.decimal_sign == '.'
assert new_zealand_dollar.grouping_places == 3
assert new_zealand_dollar.grouping_sign == ','
assert not new_zealand_dollar.international
assert new_zealand_dollar.symbol == '$'
assert new_zealand_dollar.symbol_ahead
assert new_zealand_dollar.symbol_separator == ''
assert new_zealand_dollar.localized_symbol == '$'
assert new_zealand_dollar.convertion == ''
assert new_zealand_dollar.__hash__() == hash(
(new_zealand_dollar.__class__, decimal, 'NZD', '554'))
assert new_zealand_dollar.__repr__() == (
'NewZealandDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "NZD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "$", '
'numeric_code: "554", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert new_zealand_dollar.__str__() == '$0.14'
def test_new_zealand_dollar_negative(self):
"""test_new_zealand_dollar_negative."""
amount = -100
new_zealand_dollar = NewZealandDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert new_zealand_dollar.numeric_code == '554'
assert new_zealand_dollar.alpha_code == 'NZD'
assert new_zealand_dollar.decimal_places == 2
assert new_zealand_dollar.decimal_sign == '.'
assert new_zealand_dollar.grouping_places == 3
assert new_zealand_dollar.grouping_sign == ','
assert not new_zealand_dollar.international
assert new_zealand_dollar.symbol == '$'
assert new_zealand_dollar.symbol_ahead
assert new_zealand_dollar.symbol_separator == ''
assert new_zealand_dollar.localized_symbol == '$'
assert new_zealand_dollar.convertion == ''
assert new_zealand_dollar.__hash__() == hash(
(new_zealand_dollar.__class__, decimal, 'NZD', '554'))
assert new_zealand_dollar.__repr__() == (
'NewZealandDollar(amount: -100, '
'alpha_code: "NZD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "$", '
'numeric_code: "554", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert new_zealand_dollar.__str__() == '$-100.00'
def test_new_zealand_dollar_custom(self):
"""test_new_zealand_dollar_custom."""
amount = 1000
new_zealand_dollar = NewZealandDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert new_zealand_dollar.amount == decimal
assert new_zealand_dollar.numeric_code == '554'
assert new_zealand_dollar.alpha_code == 'NZD'
assert new_zealand_dollar.decimal_places == 5
assert new_zealand_dollar.decimal_sign == ','
assert new_zealand_dollar.grouping_places == 2
assert new_zealand_dollar.grouping_sign == '.'
assert new_zealand_dollar.international
assert new_zealand_dollar.symbol == '$'
assert not new_zealand_dollar.symbol_ahead
assert new_zealand_dollar.symbol_separator == '_'
assert new_zealand_dollar.localized_symbol == '$'
assert new_zealand_dollar.convertion == ''
assert new_zealand_dollar.__hash__() == hash(
(new_zealand_dollar.__class__, decimal, 'NZD', '554'))
assert new_zealand_dollar.__repr__() == (
'NewZealandDollar(amount: 1000, '
'alpha_code: "NZD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "$", '
'numeric_code: "554", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert new_zealand_dollar.__str__() == 'NZD 10,00.00000'
def test_new_zealand_dollar_changed(self):
"""test_cnew_zealand_dollar_changed."""
new_zealand_dollar = NewZealandDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar.international = True
def test_new_zealand_dollar_math_add(self):
"""test_new_zealand_dollar_math_add."""
new_zealand_dollar_one = NewZealandDollar(amount=1)
new_zealand_dollar_two = NewZealandDollar(amount=2)
new_zealand_dollar_three = NewZealandDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency NZD and OTHER.'):
_ = new_zealand_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.NewZealandDollar\'> '
'and <class \'str\'>.')):
_ = new_zealand_dollar_one.__add__('1.00')
assert (
new_zealand_dollar_one +
new_zealand_dollar_two) == new_zealand_dollar_three
def test_new_zealand_dollar_slots(self):
"""test_new_zealand_dollar_slots."""
new_zealand_dollar = NewZealandDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'NewZealandDollar\' '
'object has no attribute \'new_variable\'')):
new_zealand_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the New Zealand Dollar CK representation."""
from multicurrency import NewZealandDollarCK
class TestNewZealandDollarCK:
"""NewZealandDollarCK currency tests."""
def test_new_zealand_dollar_ck(self):
"""test_new_zealand_dollar_ck."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
new_zealand_dollar_ck = NewZealandDollarCK(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert new_zealand_dollar_ck.amount == decimal
assert new_zealand_dollar_ck.numeric_code == '554'
assert new_zealand_dollar_ck.alpha_code == 'NZD'
assert new_zealand_dollar_ck.decimal_places == 2
assert new_zealand_dollar_ck.decimal_sign == '.'
assert new_zealand_dollar_ck.grouping_places == 3
assert new_zealand_dollar_ck.grouping_sign == ','
assert not new_zealand_dollar_ck.international
assert new_zealand_dollar_ck.symbol == '$'
assert new_zealand_dollar_ck.symbol_ahead
assert new_zealand_dollar_ck.symbol_separator == ''
assert new_zealand_dollar_ck.localized_symbol == 'CK$'
assert new_zealand_dollar_ck.convertion == ''
assert new_zealand_dollar_ck.__hash__() == hash(
(new_zealand_dollar_ck.__class__, decimal, 'NZD', '554'))
assert new_zealand_dollar_ck.__repr__() == (
'NewZealandDollarCK(amount: 0.1428571428571428571428571429, '
'alpha_code: "NZD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "CK$", '
'numeric_code: "554", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert new_zealand_dollar_ck.__str__() == '$0.14'
def test_new_zealand_dollar_ck_negative(self):
"""test_new_zealand_dollar_ck_negative."""
amount = -100
new_zealand_dollar_ck = NewZealandDollarCK(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert new_zealand_dollar_ck.numeric_code == '554'
assert new_zealand_dollar_ck.alpha_code == 'NZD'
assert new_zealand_dollar_ck.decimal_places == 2
assert new_zealand_dollar_ck.decimal_sign == '.'
assert new_zealand_dollar_ck.grouping_places == 3
assert new_zealand_dollar_ck.grouping_sign == ','
assert not new_zealand_dollar_ck.international
assert new_zealand_dollar_ck.symbol == '$'
assert new_zealand_dollar_ck.symbol_ahead
assert new_zealand_dollar_ck.symbol_separator == ''
assert new_zealand_dollar_ck.localized_symbol == 'CK$'
assert new_zealand_dollar_ck.convertion == ''
assert new_zealand_dollar_ck.__hash__() == hash(
(new_zealand_dollar_ck.__class__, decimal, 'NZD', '554'))
assert new_zealand_dollar_ck.__repr__() == (
'NewZealandDollarCK(amount: -100, '
'alpha_code: "NZD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "CK$", '
'numeric_code: "554", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert new_zealand_dollar_ck.__str__() == '$-100.00'
def test_new_zealand_dollar_ck_custom(self):
"""test_new_zealand_dollar_ck_custom."""
amount = 1000
new_zealand_dollar_ck = NewZealandDollarCK(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert new_zealand_dollar_ck.amount == decimal
assert new_zealand_dollar_ck.numeric_code == '554'
assert new_zealand_dollar_ck.alpha_code == 'NZD'
assert new_zealand_dollar_ck.decimal_places == 5
assert new_zealand_dollar_ck.decimal_sign == ','
assert new_zealand_dollar_ck.grouping_places == 2
assert new_zealand_dollar_ck.grouping_sign == '.'
assert new_zealand_dollar_ck.international
assert new_zealand_dollar_ck.symbol == '$'
assert not new_zealand_dollar_ck.symbol_ahead
assert new_zealand_dollar_ck.symbol_separator == '_'
assert new_zealand_dollar_ck.localized_symbol == 'CK$'
assert new_zealand_dollar_ck.convertion == ''
assert new_zealand_dollar_ck.__hash__() == hash(
(new_zealand_dollar_ck.__class__, decimal, 'NZD', '554'))
assert new_zealand_dollar_ck.__repr__() == (
'NewZealandDollarCK(amount: 1000, '
'alpha_code: "NZD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "CK$", '
'numeric_code: "554", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert new_zealand_dollar_ck.__str__() == 'NZD 10,00.00000'
def test_new_zealand_dollar_ck_changed(self):
"""test_cnew_zealand_dollar_ck_changed."""
new_zealand_dollar_ck = NewZealandDollarCK(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_ck.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_ck.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_ck.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_ck.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_ck.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_ck.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_ck.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_ck.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_ck.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_ck.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_ck.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_ck.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_ck.international = True
def test_new_zealand_dollar_ck_math_add(self):
"""test_new_zealand_dollar_ck_math_add."""
new_zealand_dollar_ck_one = NewZealandDollarCK(amount=1)
new_zealand_dollar_ck_two = NewZealandDollarCK(amount=2)
new_zealand_dollar_ck_three = NewZealandDollarCK(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency NZD and OTHER.'):
_ = new_zealand_dollar_ck_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.NewZealandDollarCK\'> '
'and <class \'str\'>.')):
_ = new_zealand_dollar_ck_one.__add__('1.00')
assert (
new_zealand_dollar_ck_one +
new_zealand_dollar_ck_two) == new_zealand_dollar_ck_three
def test_new_zealand_dollar_ck_slots(self):
"""test_new_zealand_dollar_ck_slots."""
new_zealand_dollar_ck = NewZealandDollarCK(amount=1000)
with raises(
AttributeError,
match=(
'\'NewZealandDollarCK\' '
'object has no attribute \'new_variable\'')):
new_zealand_dollar_ck.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the New Zealand Dollar NZ representation."""
from multicurrency import NewZealandDollarNZ
class TestNewZealandDollarNZ:
"""NewZealandDollarNZ currency tests."""
def test_new_zealand_dollar_nz(self):
"""test_new_zealand_dollar_nz."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
new_zealand_dollar_nz = NewZealandDollarNZ(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert new_zealand_dollar_nz.amount == decimal
assert new_zealand_dollar_nz.numeric_code == '554'
assert new_zealand_dollar_nz.alpha_code == 'NZD'
assert new_zealand_dollar_nz.decimal_places == 2
assert new_zealand_dollar_nz.decimal_sign == '.'
assert new_zealand_dollar_nz.grouping_places == 3
assert new_zealand_dollar_nz.grouping_sign == ','
assert not new_zealand_dollar_nz.international
assert new_zealand_dollar_nz.symbol == '$'
assert new_zealand_dollar_nz.symbol_ahead
assert new_zealand_dollar_nz.symbol_separator == ''
assert new_zealand_dollar_nz.localized_symbol == 'NZ$'
assert new_zealand_dollar_nz.convertion == ''
assert new_zealand_dollar_nz.__hash__() == hash(
(new_zealand_dollar_nz.__class__, decimal, 'NZD', '554'))
assert new_zealand_dollar_nz.__repr__() == (
'NewZealandDollarNZ(amount: 0.1428571428571428571428571429, '
'alpha_code: "NZD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "NZ$", '
'numeric_code: "554", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert new_zealand_dollar_nz.__str__() == '$0.14'
def test_new_zealand_dollar_nz_negative(self):
"""test_new_zealand_dollar_nz_negative."""
amount = -100
new_zealand_dollar_nz = NewZealandDollarNZ(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert new_zealand_dollar_nz.numeric_code == '554'
assert new_zealand_dollar_nz.alpha_code == 'NZD'
assert new_zealand_dollar_nz.decimal_places == 2
assert new_zealand_dollar_nz.decimal_sign == '.'
assert new_zealand_dollar_nz.grouping_places == 3
assert new_zealand_dollar_nz.grouping_sign == ','
assert not new_zealand_dollar_nz.international
assert new_zealand_dollar_nz.symbol == '$'
assert new_zealand_dollar_nz.symbol_ahead
assert new_zealand_dollar_nz.symbol_separator == ''
assert new_zealand_dollar_nz.localized_symbol == 'NZ$'
assert new_zealand_dollar_nz.convertion == ''
assert new_zealand_dollar_nz.__hash__() == hash(
(new_zealand_dollar_nz.__class__, decimal, 'NZD', '554'))
assert new_zealand_dollar_nz.__repr__() == (
'NewZealandDollarNZ(amount: -100, '
'alpha_code: "NZD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "NZ$", '
'numeric_code: "554", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert new_zealand_dollar_nz.__str__() == '$-100.00'
def test_new_zealand_dollar_nz_custom(self):
"""test_new_zealand_dollar_nz_custom."""
amount = 1000
new_zealand_dollar_nz = NewZealandDollarNZ(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert new_zealand_dollar_nz.amount == decimal
assert new_zealand_dollar_nz.numeric_code == '554'
assert new_zealand_dollar_nz.alpha_code == 'NZD'
assert new_zealand_dollar_nz.decimal_places == 5
assert new_zealand_dollar_nz.decimal_sign == ','
assert new_zealand_dollar_nz.grouping_places == 2
assert new_zealand_dollar_nz.grouping_sign == '.'
assert new_zealand_dollar_nz.international
assert new_zealand_dollar_nz.symbol == '$'
assert not new_zealand_dollar_nz.symbol_ahead
assert new_zealand_dollar_nz.symbol_separator == '_'
assert new_zealand_dollar_nz.localized_symbol == 'NZ$'
assert new_zealand_dollar_nz.convertion == ''
assert new_zealand_dollar_nz.__hash__() == hash(
(new_zealand_dollar_nz.__class__, decimal, 'NZD', '554'))
assert new_zealand_dollar_nz.__repr__() == (
'NewZealandDollarNZ(amount: 1000, '
'alpha_code: "NZD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "NZ$", '
'numeric_code: "554", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert new_zealand_dollar_nz.__str__() == 'NZD 10,00.00000'
def test_new_zealand_dollar_nz_changed(self):
"""test_cnew_zealand_dollar_nz_changed."""
new_zealand_dollar_nz = NewZealandDollarNZ(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nz.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nz.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nz.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nz.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nz.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nz.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nz.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nz.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nz.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nz.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nz.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nz.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nz.international = True
def test_new_zealand_dollar_nz_math_add(self):
"""test_new_zealand_dollar_nz_math_add."""
new_zealand_dollar_nz_one = NewZealandDollarNZ(amount=1)
new_zealand_dollar_nz_two = NewZealandDollarNZ(amount=2)
new_zealand_dollar_nz_three = NewZealandDollarNZ(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency NZD and OTHER.'):
_ = new_zealand_dollar_nz_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.NewZealandDollarNZ\'> '
'and <class \'str\'>.')):
_ = new_zealand_dollar_nz_one.__add__('1.00')
assert (
new_zealand_dollar_nz_one +
new_zealand_dollar_nz_two) == new_zealand_dollar_nz_three
def test_new_zealand_dollar_nz_slots(self):
"""test_new_zealand_dollar_nz_slots."""
new_zealand_dollar_nz = NewZealandDollarNZ(amount=1000)
with raises(
AttributeError,
match=(
'\'NewZealandDollarNZ\' '
'object has no attribute \'new_variable\'')):
new_zealand_dollar_nz.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the New Zealand Dollar NU representation."""
from multicurrency import NewZealandDollarNU
class TestNewZealandDollarNU:
"""NewZealandDollarNU currency tests."""
def test_new_zealand_dollar_nu(self):
"""test_new_zealand_dollar_nu."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
new_zealand_dollar_nu = NewZealandDollarNU(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert new_zealand_dollar_nu.amount == decimal
assert new_zealand_dollar_nu.numeric_code == '554'
assert new_zealand_dollar_nu.alpha_code == 'NZD'
assert new_zealand_dollar_nu.decimal_places == 2
assert new_zealand_dollar_nu.decimal_sign == '.'
assert new_zealand_dollar_nu.grouping_places == 3
assert new_zealand_dollar_nu.grouping_sign == ','
assert not new_zealand_dollar_nu.international
assert new_zealand_dollar_nu.symbol == '$'
assert new_zealand_dollar_nu.symbol_ahead
assert new_zealand_dollar_nu.symbol_separator == ''
assert new_zealand_dollar_nu.localized_symbol == 'NU$'
assert new_zealand_dollar_nu.convertion == ''
assert new_zealand_dollar_nu.__hash__() == hash(
(new_zealand_dollar_nu.__class__, decimal, 'NZD', '554'))
assert new_zealand_dollar_nu.__repr__() == (
'NewZealandDollarNU(amount: 0.1428571428571428571428571429, '
'alpha_code: "NZD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "NU$", '
'numeric_code: "554", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert new_zealand_dollar_nu.__str__() == '$0.14'
def test_new_zealand_dollar_nu_negative(self):
"""test_new_zealand_dollar_nu_negative."""
amount = -100
new_zealand_dollar_nu = NewZealandDollarNU(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert new_zealand_dollar_nu.numeric_code == '554'
assert new_zealand_dollar_nu.alpha_code == 'NZD'
assert new_zealand_dollar_nu.decimal_places == 2
assert new_zealand_dollar_nu.decimal_sign == '.'
assert new_zealand_dollar_nu.grouping_places == 3
assert new_zealand_dollar_nu.grouping_sign == ','
assert not new_zealand_dollar_nu.international
assert new_zealand_dollar_nu.symbol == '$'
assert new_zealand_dollar_nu.symbol_ahead
assert new_zealand_dollar_nu.symbol_separator == ''
assert new_zealand_dollar_nu.localized_symbol == 'NU$'
assert new_zealand_dollar_nu.convertion == ''
assert new_zealand_dollar_nu.__hash__() == hash(
(new_zealand_dollar_nu.__class__, decimal, 'NZD', '554'))
assert new_zealand_dollar_nu.__repr__() == (
'NewZealandDollarNU(amount: -100, '
'alpha_code: "NZD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "NU$", '
'numeric_code: "554", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert new_zealand_dollar_nu.__str__() == '$-100.00'
def test_new_zealand_dollar_nu_custom(self):
"""test_new_zealand_dollar_nu_custom."""
amount = 1000
new_zealand_dollar_nu = NewZealandDollarNU(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert new_zealand_dollar_nu.amount == decimal
assert new_zealand_dollar_nu.numeric_code == '554'
assert new_zealand_dollar_nu.alpha_code == 'NZD'
assert new_zealand_dollar_nu.decimal_places == 5
assert new_zealand_dollar_nu.decimal_sign == ','
assert new_zealand_dollar_nu.grouping_places == 2
assert new_zealand_dollar_nu.grouping_sign == '.'
assert new_zealand_dollar_nu.international
assert new_zealand_dollar_nu.symbol == '$'
assert not new_zealand_dollar_nu.symbol_ahead
assert new_zealand_dollar_nu.symbol_separator == '_'
assert new_zealand_dollar_nu.localized_symbol == 'NU$'
assert new_zealand_dollar_nu.convertion == ''
assert new_zealand_dollar_nu.__hash__() == hash(
(new_zealand_dollar_nu.__class__, decimal, 'NZD', '554'))
assert new_zealand_dollar_nu.__repr__() == (
'NewZealandDollarNU(amount: 1000, '
'alpha_code: "NZD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "NU$", '
'numeric_code: "554", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert new_zealand_dollar_nu.__str__() == 'NZD 10,00.00000'
def test_new_zealand_dollar_nu_changed(self):
"""test_cnew_zealand_dollar_nu_changed."""
new_zealand_dollar_nu = NewZealandDollarNU(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nu.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nu.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nu.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nu.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nu.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nu.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nu.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nu.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nu.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nu.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nu.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nu.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_nu.international = True
def test_new_zealand_dollar_nu_math_add(self):
"""test_new_zealand_dollar_nu_math_add."""
new_zealand_dollar_nu_one = NewZealandDollarNU(amount=1)
new_zealand_dollar_nu_two = NewZealandDollarNU(amount=2)
new_zealand_dollar_nu_three = NewZealandDollarNU(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency NZD and OTHER.'):
_ = new_zealand_dollar_nu_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.NewZealandDollarNU\'> '
'and <class \'str\'>.')):
_ = new_zealand_dollar_nu_one.__add__('1.00')
assert (
new_zealand_dollar_nu_one +
new_zealand_dollar_nu_two) == new_zealand_dollar_nu_three
def test_new_zealand_dollar_nu_slots(self):
"""test_new_zealand_dollar_nu_slots."""
new_zealand_dollar_nu = NewZealandDollarNU(amount=1000)
with raises(
AttributeError,
match=(
'\'NewZealandDollarNU\' '
'object has no attribute \'new_variable\'')):
new_zealand_dollar_nu.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the New Zealand Dollar PN representation."""
from multicurrency import NewZealandDollarPN
class TestNewZealandDollarPN:
"""NewZealandDollarPN currency tests."""
def test_new_zealand_dollar_pn(self):
"""test_new_zealand_dollar_pn."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
new_zealand_dollar_pn = NewZealandDollarPN(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert new_zealand_dollar_pn.amount == decimal
assert new_zealand_dollar_pn.numeric_code == '554'
assert new_zealand_dollar_pn.alpha_code == 'NZD'
assert new_zealand_dollar_pn.decimal_places == 2
assert new_zealand_dollar_pn.decimal_sign == '.'
assert new_zealand_dollar_pn.grouping_places == 3
assert new_zealand_dollar_pn.grouping_sign == ','
assert not new_zealand_dollar_pn.international
assert new_zealand_dollar_pn.symbol == '$'
assert new_zealand_dollar_pn.symbol_ahead
assert new_zealand_dollar_pn.symbol_separator == ''
assert new_zealand_dollar_pn.localized_symbol == 'PN$'
assert new_zealand_dollar_pn.convertion == ''
assert new_zealand_dollar_pn.__hash__() == hash(
(new_zealand_dollar_pn.__class__, decimal, 'NZD', '554'))
assert new_zealand_dollar_pn.__repr__() == (
'NewZealandDollarPN(amount: 0.1428571428571428571428571429, '
'alpha_code: "NZD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "PN$", '
'numeric_code: "554", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert new_zealand_dollar_pn.__str__() == '$0.14'
def test_new_zealand_dollar_pn_negative(self):
"""test_new_zealand_dollar_pn_negative."""
amount = -100
new_zealand_dollar_pn = NewZealandDollarPN(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert new_zealand_dollar_pn.numeric_code == '554'
assert new_zealand_dollar_pn.alpha_code == 'NZD'
assert new_zealand_dollar_pn.decimal_places == 2
assert new_zealand_dollar_pn.decimal_sign == '.'
assert new_zealand_dollar_pn.grouping_places == 3
assert new_zealand_dollar_pn.grouping_sign == ','
assert not new_zealand_dollar_pn.international
assert new_zealand_dollar_pn.symbol == '$'
assert new_zealand_dollar_pn.symbol_ahead
assert new_zealand_dollar_pn.symbol_separator == ''
assert new_zealand_dollar_pn.localized_symbol == 'PN$'
assert new_zealand_dollar_pn.convertion == ''
assert new_zealand_dollar_pn.__hash__() == hash(
(new_zealand_dollar_pn.__class__, decimal, 'NZD', '554'))
assert new_zealand_dollar_pn.__repr__() == (
'NewZealandDollarPN(amount: -100, '
'alpha_code: "NZD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "PN$", '
'numeric_code: "554", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert new_zealand_dollar_pn.__str__() == '$-100.00'
def test_new_zealand_dollar_pn_custom(self):
"""test_new_zealand_dollar_pn_custom."""
amount = 1000
new_zealand_dollar_pn = NewZealandDollarPN(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert new_zealand_dollar_pn.amount == decimal
assert new_zealand_dollar_pn.numeric_code == '554'
assert new_zealand_dollar_pn.alpha_code == 'NZD'
assert new_zealand_dollar_pn.decimal_places == 5
assert new_zealand_dollar_pn.decimal_sign == ','
assert new_zealand_dollar_pn.grouping_places == 2
assert new_zealand_dollar_pn.grouping_sign == '.'
assert new_zealand_dollar_pn.international
assert new_zealand_dollar_pn.symbol == '$'
assert not new_zealand_dollar_pn.symbol_ahead
assert new_zealand_dollar_pn.symbol_separator == '_'
assert new_zealand_dollar_pn.localized_symbol == 'PN$'
assert new_zealand_dollar_pn.convertion == ''
assert new_zealand_dollar_pn.__hash__() == hash(
(new_zealand_dollar_pn.__class__, decimal, 'NZD', '554'))
assert new_zealand_dollar_pn.__repr__() == (
'NewZealandDollarPN(amount: 1000, '
'alpha_code: "NZD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "PN$", '
'numeric_code: "554", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert new_zealand_dollar_pn.__str__() == 'NZD 10,00.00000'
def test_new_zealand_dollar_pn_changed(self):
"""test_cnew_zealand_dollar_pn_changed."""
new_zealand_dollar_pn = NewZealandDollarPN(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_pn.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_pn.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_pn.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_pn.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_pn.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_pn.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_pn.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_pn.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_pn.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_pn.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_pn.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_pn.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
new_zealand_dollar_pn.international = True
def test_new_zealand_dollar_pn_math_add(self):
"""test_new_zealand_dollar_pn_math_add."""
new_zealand_dollar_pn_one = NewZealandDollarPN(amount=1)
new_zealand_dollar_pn_two = NewZealandDollarPN(amount=2)
new_zealand_dollar_pn_three = NewZealandDollarPN(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency NZD and OTHER.'):
_ = new_zealand_dollar_pn_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.NewZealandDollarPN\'> '
'and <class \'str\'>.')):
_ = new_zealand_dollar_pn_one.__add__('1.00')
assert (
new_zealand_dollar_pn_one +
new_zealand_dollar_pn_two) == new_zealand_dollar_pn_three
def test_new_zealand_dollar_pn_slots(self):
"""test_new_zealand_dollar_pn_slots."""
new_zealand_dollar_pn = NewZealandDollarPN(amount=1000)
with raises(
AttributeError,
match=(
'\'NewZealandDollarPN\' '
'object has no attribute \'new_variable\'')):
new_zealand_dollar_pn.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Solomon Islands Dollar representation."""
from multicurrency import SolomonIslandsDollar
class TestSolomonIslandsDollar:
"""SolomonIslandsDollar currency tests."""
def test_solomon_islands_dollar(self):
"""test_solomon_islands_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
solomon_islands_dollar = SolomonIslandsDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert solomon_islands_dollar.amount == decimal
assert solomon_islands_dollar.numeric_code == '090'
assert solomon_islands_dollar.alpha_code == 'SBD'
assert solomon_islands_dollar.decimal_places == 2
assert solomon_islands_dollar.decimal_sign == '.'
assert solomon_islands_dollar.grouping_places == 3
assert solomon_islands_dollar.grouping_sign == ','
assert not solomon_islands_dollar.international
assert solomon_islands_dollar.symbol == '$'
assert solomon_islands_dollar.symbol_ahead
assert solomon_islands_dollar.symbol_separator == ''
assert solomon_islands_dollar.localized_symbol == 'SB$'
assert solomon_islands_dollar.convertion == ''
assert solomon_islands_dollar.__hash__() == hash(
(solomon_islands_dollar.__class__, decimal, 'SBD', '090'))
assert solomon_islands_dollar.__repr__() == (
'SolomonIslandsDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "SBD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "SB$", '
'numeric_code: "090", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert solomon_islands_dollar.__str__() == '$0.14'
def test_solomon_islands_dollar_negative(self):
"""test_solomon_islands_dollar_negative."""
amount = -100
solomon_islands_dollar = SolomonIslandsDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert solomon_islands_dollar.numeric_code == '090'
assert solomon_islands_dollar.alpha_code == 'SBD'
assert solomon_islands_dollar.decimal_places == 2
assert solomon_islands_dollar.decimal_sign == '.'
assert solomon_islands_dollar.grouping_places == 3
assert solomon_islands_dollar.grouping_sign == ','
assert not solomon_islands_dollar.international
assert solomon_islands_dollar.symbol == '$'
assert solomon_islands_dollar.symbol_ahead
assert solomon_islands_dollar.symbol_separator == ''
assert solomon_islands_dollar.localized_symbol == 'SB$'
assert solomon_islands_dollar.convertion == ''
assert solomon_islands_dollar.__hash__() == hash(
(solomon_islands_dollar.__class__, decimal, 'SBD', '090'))
assert solomon_islands_dollar.__repr__() == (
'SolomonIslandsDollar(amount: -100, '
'alpha_code: "SBD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "SB$", '
'numeric_code: "090", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert solomon_islands_dollar.__str__() == '$-100.00'
def test_solomon_islands_dollar_custom(self):
"""test_solomon_islands_dollar_custom."""
amount = 1000
solomon_islands_dollar = SolomonIslandsDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert solomon_islands_dollar.amount == decimal
assert solomon_islands_dollar.numeric_code == '090'
assert solomon_islands_dollar.alpha_code == 'SBD'
assert solomon_islands_dollar.decimal_places == 5
assert solomon_islands_dollar.decimal_sign == ','
assert solomon_islands_dollar.grouping_places == 2
assert solomon_islands_dollar.grouping_sign == '.'
assert solomon_islands_dollar.international
assert solomon_islands_dollar.symbol == '$'
assert not solomon_islands_dollar.symbol_ahead
assert solomon_islands_dollar.symbol_separator == '_'
assert solomon_islands_dollar.localized_symbol == 'SB$'
assert solomon_islands_dollar.convertion == ''
assert solomon_islands_dollar.__hash__() == hash(
(solomon_islands_dollar.__class__, decimal, 'SBD', '090'))
assert solomon_islands_dollar.__repr__() == (
'SolomonIslandsDollar(amount: 1000, '
'alpha_code: "SBD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "SB$", '
'numeric_code: "090", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert solomon_islands_dollar.__str__() == 'SBD 10,00.00000'
def test_solomon_islands_dollar_changed(self):
"""test_csolomon_islands_dollar_changed."""
solomon_islands_dollar = SolomonIslandsDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
solomon_islands_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
solomon_islands_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
solomon_islands_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
solomon_islands_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
solomon_islands_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
solomon_islands_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
solomon_islands_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
solomon_islands_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
solomon_islands_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
solomon_islands_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
solomon_islands_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
solomon_islands_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
solomon_islands_dollar.international = True
def test_solomon_islands_dollar_math_add(self):
"""test_solomon_islands_dollar_math_add."""
solomon_islands_dollar_one = SolomonIslandsDollar(amount=1)
solomon_islands_dollar_two = SolomonIslandsDollar(amount=2)
solomon_islands_dollar_three = SolomonIslandsDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency SBD and OTHER.'):
_ = solomon_islands_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.SolomonIslandsDollar\'> '
'and <class \'str\'>.')):
_ = solomon_islands_dollar_one.__add__('1.00')
assert (
solomon_islands_dollar_one +
solomon_islands_dollar_two) == solomon_islands_dollar_three
def test_solomon_islands_dollar_slots(self):
"""test_solomon_islands_dollar_slots."""
solomon_islands_dollar = SolomonIslandsDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'SolomonIslandsDollar\' '
'object has no attribute \'new_variable\'')):
solomon_islands_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Singapore Dollar representation."""
from multicurrency import SingaporeDollar
class TestSingaporeDollar:
"""SingaporeDollar currency tests."""
def test_singapore_dollar(self):
"""test_singapore_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
singapore_dollar = SingaporeDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert singapore_dollar.amount == decimal
assert singapore_dollar.numeric_code == '702'
assert singapore_dollar.alpha_code == 'SGD'
assert singapore_dollar.decimal_places == 2
assert singapore_dollar.decimal_sign == '.'
assert singapore_dollar.grouping_places == 3
assert singapore_dollar.grouping_sign == ','
assert not singapore_dollar.international
assert singapore_dollar.symbol == '$'
assert singapore_dollar.symbol_ahead
assert singapore_dollar.symbol_separator == ''
assert singapore_dollar.localized_symbol == '$'
assert singapore_dollar.convertion == ''
assert singapore_dollar.__hash__() == hash(
(singapore_dollar.__class__, decimal, 'SGD', '702'))
assert singapore_dollar.__repr__() == (
'SingaporeDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "SGD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "$", '
'numeric_code: "702", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert singapore_dollar.__str__() == '$0.14'
def test_singapore_dollar_negative(self):
"""test_singapore_dollar_negative."""
amount = -100
singapore_dollar = SingaporeDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert singapore_dollar.numeric_code == '702'
assert singapore_dollar.alpha_code == 'SGD'
assert singapore_dollar.decimal_places == 2
assert singapore_dollar.decimal_sign == '.'
assert singapore_dollar.grouping_places == 3
assert singapore_dollar.grouping_sign == ','
assert not singapore_dollar.international
assert singapore_dollar.symbol == '$'
assert singapore_dollar.symbol_ahead
assert singapore_dollar.symbol_separator == ''
assert singapore_dollar.localized_symbol == '$'
assert singapore_dollar.convertion == ''
assert singapore_dollar.__hash__() == hash(
(singapore_dollar.__class__, decimal, 'SGD', '702'))
assert singapore_dollar.__repr__() == (
'SingaporeDollar(amount: -100, '
'alpha_code: "SGD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "$", '
'numeric_code: "702", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert singapore_dollar.__str__() == '$-100.00'
def test_singapore_dollar_custom(self):
"""test_singapore_dollar_custom."""
amount = 1000
singapore_dollar = SingaporeDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert singapore_dollar.amount == decimal
assert singapore_dollar.numeric_code == '702'
assert singapore_dollar.alpha_code == 'SGD'
assert singapore_dollar.decimal_places == 5
assert singapore_dollar.decimal_sign == ','
assert singapore_dollar.grouping_places == 2
assert singapore_dollar.grouping_sign == '.'
assert singapore_dollar.international
assert singapore_dollar.symbol == '$'
assert not singapore_dollar.symbol_ahead
assert singapore_dollar.symbol_separator == '_'
assert singapore_dollar.localized_symbol == '$'
assert singapore_dollar.convertion == ''
assert singapore_dollar.__hash__() == hash(
(singapore_dollar.__class__, decimal, 'SGD', '702'))
assert singapore_dollar.__repr__() == (
'SingaporeDollar(amount: 1000, '
'alpha_code: "SGD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "$", '
'numeric_code: "702", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert singapore_dollar.__str__() == 'SGD 10,00.00000'
def test_singapore_dollar_changed(self):
"""test_csingapore_dollar_changed."""
singapore_dollar = SingaporeDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar.international = True
def test_singapore_dollar_math_add(self):
"""test_singapore_dollar_math_add."""
singapore_dollar_one = SingaporeDollar(amount=1)
singapore_dollar_two = SingaporeDollar(amount=2)
singapore_dollar_three = SingaporeDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency SGD and OTHER.'):
_ = singapore_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.SingaporeDollar\'> '
'and <class \'str\'>.')):
_ = singapore_dollar_one.__add__('1.00')
assert (
singapore_dollar_one +
singapore_dollar_two) == singapore_dollar_three
def test_singapore_dollar_slots(self):
"""test_singapore_dollar_slots."""
singapore_dollar = SingaporeDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'SingaporeDollar\' '
'object has no attribute \'new_variable\'')):
singapore_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Singapore Dollar BN representation."""
from multicurrency import SingaporeDollarBN
class TestSingaporeDollarBN:
"""SingaporeDollarBN currency tests."""
def test_singapore_dollar_bn(self):
"""test_singapore_dollar_bn."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
singapore_dollar_bn = SingaporeDollarBN(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert singapore_dollar_bn.amount == decimal
assert singapore_dollar_bn.numeric_code == '702'
assert singapore_dollar_bn.alpha_code == 'SGD'
assert singapore_dollar_bn.decimal_places == 2
assert singapore_dollar_bn.decimal_sign == '.'
assert singapore_dollar_bn.grouping_places == 3
assert singapore_dollar_bn.grouping_sign == ','
assert not singapore_dollar_bn.international
assert singapore_dollar_bn.symbol == '$'
assert singapore_dollar_bn.symbol_ahead
assert singapore_dollar_bn.symbol_separator == ''
assert singapore_dollar_bn.localized_symbol == 'BN$'
assert singapore_dollar_bn.convertion == ''
assert singapore_dollar_bn.__hash__() == hash(
(singapore_dollar_bn.__class__, decimal, 'SGD', '702'))
assert singapore_dollar_bn.__repr__() == (
'SingaporeDollarBN(amount: 0.1428571428571428571428571429, '
'alpha_code: "SGD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "BN$", '
'numeric_code: "702", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert singapore_dollar_bn.__str__() == '$0.14'
def test_singapore_dollar_bn_negative(self):
"""test_singapore_dollar_bn_negative."""
amount = -100
singapore_dollar_bn = SingaporeDollarBN(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert singapore_dollar_bn.numeric_code == '702'
assert singapore_dollar_bn.alpha_code == 'SGD'
assert singapore_dollar_bn.decimal_places == 2
assert singapore_dollar_bn.decimal_sign == '.'
assert singapore_dollar_bn.grouping_places == 3
assert singapore_dollar_bn.grouping_sign == ','
assert not singapore_dollar_bn.international
assert singapore_dollar_bn.symbol == '$'
assert singapore_dollar_bn.symbol_ahead
assert singapore_dollar_bn.symbol_separator == ''
assert singapore_dollar_bn.localized_symbol == 'BN$'
assert singapore_dollar_bn.convertion == ''
assert singapore_dollar_bn.__hash__() == hash(
(singapore_dollar_bn.__class__, decimal, 'SGD', '702'))
assert singapore_dollar_bn.__repr__() == (
'SingaporeDollarBN(amount: -100, '
'alpha_code: "SGD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "BN$", '
'numeric_code: "702", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert singapore_dollar_bn.__str__() == '$-100.00'
def test_singapore_dollar_bn_custom(self):
"""test_singapore_dollar_bn_custom."""
amount = 1000
singapore_dollar_bn = SingaporeDollarBN(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert singapore_dollar_bn.amount == decimal
assert singapore_dollar_bn.numeric_code == '702'
assert singapore_dollar_bn.alpha_code == 'SGD'
assert singapore_dollar_bn.decimal_places == 5
assert singapore_dollar_bn.decimal_sign == ','
assert singapore_dollar_bn.grouping_places == 2
assert singapore_dollar_bn.grouping_sign == '.'
assert singapore_dollar_bn.international
assert singapore_dollar_bn.symbol == '$'
assert not singapore_dollar_bn.symbol_ahead
assert singapore_dollar_bn.symbol_separator == '_'
assert singapore_dollar_bn.localized_symbol == 'BN$'
assert singapore_dollar_bn.convertion == ''
assert singapore_dollar_bn.__hash__() == hash(
(singapore_dollar_bn.__class__, decimal, 'SGD', '702'))
assert singapore_dollar_bn.__repr__() == (
'SingaporeDollarBN(amount: 1000, '
'alpha_code: "SGD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "BN$", '
'numeric_code: "702", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert singapore_dollar_bn.__str__() == 'SGD 10,00.00000'
def test_singapore_dollar_bn_changed(self):
"""test_csingapore_dollar_bn_changed."""
singapore_dollar_bn = SingaporeDollarBN(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_bn.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_bn.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_bn.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_bn.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_bn.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_bn.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_bn.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_bn.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_bn.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_bn.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_bn.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_bn.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_bn.international = True
def test_singapore_dollar_bn_math_add(self):
"""test_singapore_dollar_bn_math_add."""
singapore_dollar_bn_one = SingaporeDollarBN(amount=1)
singapore_dollar_bn_two = SingaporeDollarBN(amount=2)
singapore_dollar_bn_three = SingaporeDollarBN(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency SGD and OTHER.'):
_ = singapore_dollar_bn_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.SingaporeDollarBN\'> '
'and <class \'str\'>.')):
_ = singapore_dollar_bn_one.__add__('1.00')
assert (
singapore_dollar_bn_one +
singapore_dollar_bn_two) == singapore_dollar_bn_three
def test_singapore_dollar_bn_slots(self):
"""test_singapore_dollar_bn_slots."""
singapore_dollar_bn = SingaporeDollarBN(amount=1000)
with raises(
AttributeError,
match=(
'\'SingaporeDollarBN\' '
'object has no attribute \'new_variable\'')):
singapore_dollar_bn.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Singapore Dollar SG representation."""
from multicurrency import SingaporeDollarSG
class TestSingaporeDollarSG:
"""SingaporeDollarSG currency tests."""
def test_singapore_dollar_sg(self):
"""test_singapore_dollar_sg."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
singapore_dollar_sg = SingaporeDollarSG(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert singapore_dollar_sg.amount == decimal
assert singapore_dollar_sg.numeric_code == '702'
assert singapore_dollar_sg.alpha_code == 'SGD'
assert singapore_dollar_sg.decimal_places == 2
assert singapore_dollar_sg.decimal_sign == '.'
assert singapore_dollar_sg.grouping_places == 3
assert singapore_dollar_sg.grouping_sign == ','
assert not singapore_dollar_sg.international
assert singapore_dollar_sg.symbol == '$'
assert singapore_dollar_sg.symbol_ahead
assert singapore_dollar_sg.symbol_separator == ''
assert singapore_dollar_sg.localized_symbol == 'SG$'
assert singapore_dollar_sg.convertion == ''
assert singapore_dollar_sg.__hash__() == hash(
(singapore_dollar_sg.__class__, decimal, 'SGD', '702'))
assert singapore_dollar_sg.__repr__() == (
'SingaporeDollarSG(amount: 0.1428571428571428571428571429, '
'alpha_code: "SGD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "SG$", '
'numeric_code: "702", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert singapore_dollar_sg.__str__() == '$0.14'
def test_singapore_dollar_sg_negative(self):
"""test_singapore_dollar_sg_negative."""
amount = -100
singapore_dollar_sg = SingaporeDollarSG(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert singapore_dollar_sg.numeric_code == '702'
assert singapore_dollar_sg.alpha_code == 'SGD'
assert singapore_dollar_sg.decimal_places == 2
assert singapore_dollar_sg.decimal_sign == '.'
assert singapore_dollar_sg.grouping_places == 3
assert singapore_dollar_sg.grouping_sign == ','
assert not singapore_dollar_sg.international
assert singapore_dollar_sg.symbol == '$'
assert singapore_dollar_sg.symbol_ahead
assert singapore_dollar_sg.symbol_separator == ''
assert singapore_dollar_sg.localized_symbol == 'SG$'
assert singapore_dollar_sg.convertion == ''
assert singapore_dollar_sg.__hash__() == hash(
(singapore_dollar_sg.__class__, decimal, 'SGD', '702'))
assert singapore_dollar_sg.__repr__() == (
'SingaporeDollarSG(amount: -100, '
'alpha_code: "SGD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "SG$", '
'numeric_code: "702", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert singapore_dollar_sg.__str__() == '$-100.00'
def test_singapore_dollar_sg_custom(self):
"""test_singapore_dollar_sg_custom."""
amount = 1000
singapore_dollar_sg = SingaporeDollarSG(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert singapore_dollar_sg.amount == decimal
assert singapore_dollar_sg.numeric_code == '702'
assert singapore_dollar_sg.alpha_code == 'SGD'
assert singapore_dollar_sg.decimal_places == 5
assert singapore_dollar_sg.decimal_sign == ','
assert singapore_dollar_sg.grouping_places == 2
assert singapore_dollar_sg.grouping_sign == '.'
assert singapore_dollar_sg.international
assert singapore_dollar_sg.symbol == '$'
assert not singapore_dollar_sg.symbol_ahead
assert singapore_dollar_sg.symbol_separator == '_'
assert singapore_dollar_sg.localized_symbol == 'SG$'
assert singapore_dollar_sg.convertion == ''
assert singapore_dollar_sg.__hash__() == hash(
(singapore_dollar_sg.__class__, decimal, 'SGD', '702'))
assert singapore_dollar_sg.__repr__() == (
'SingaporeDollarSG(amount: 1000, '
'alpha_code: "SGD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "SG$", '
'numeric_code: "702", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert singapore_dollar_sg.__str__() == 'SGD 10,00.00000'
def test_singapore_dollar_sg_changed(self):
"""test_csingapore_dollar_sg_changed."""
singapore_dollar_sg = SingaporeDollarSG(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_sg.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_sg.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_sg.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_sg.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_sg.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_sg.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_sg.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_sg.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_sg.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_sg.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_sg.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_sg.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
singapore_dollar_sg.international = True
def test_singapore_dollar_sg_math_add(self):
"""test_singapore_dollar_sg_math_add."""
singapore_dollar_sg_one = SingaporeDollarSG(amount=1)
singapore_dollar_sg_two = SingaporeDollarSG(amount=2)
singapore_dollar_sg_three = SingaporeDollarSG(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency SGD and OTHER.'):
_ = singapore_dollar_sg_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.SingaporeDollarSG\'> '
'and <class \'str\'>.')):
_ = singapore_dollar_sg_one.__add__('1.00')
assert (
singapore_dollar_sg_one +
singapore_dollar_sg_two) == singapore_dollar_sg_three
def test_singapore_dollar_sg_slots(self):
"""test_singapore_dollar_sg_slots."""
singapore_dollar_sg = SingaporeDollarSG(amount=1000)
with raises(
AttributeError,
match=(
'\'SingaporeDollarSG\' '
'object has no attribute \'new_variable\'')):
singapore_dollar_sg.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Suriname Dollar representation."""
from multicurrency import SurinameDollar
class TestSurinameDollar:
"""SurinameDollar currency tests."""
def test_suriname_dollar(self):
"""test_suriname_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
suriname_dollar = SurinameDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert suriname_dollar.amount == decimal
assert suriname_dollar.numeric_code == '968'
assert suriname_dollar.alpha_code == 'SRD'
assert suriname_dollar.decimal_places == 2
assert suriname_dollar.decimal_sign == ','
assert suriname_dollar.grouping_places == 3
assert suriname_dollar.grouping_sign == '.'
assert not suriname_dollar.international
assert suriname_dollar.symbol == '$'
assert suriname_dollar.symbol_ahead
assert suriname_dollar.symbol_separator == '\u00A0'
assert suriname_dollar.localized_symbol == 'SR$'
assert suriname_dollar.convertion == ''
assert suriname_dollar.__hash__() == hash(
(suriname_dollar.__class__, decimal, 'SRD', '968'))
assert suriname_dollar.__repr__() == (
'SurinameDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "SRD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "\u00A0", '
'localized_symbol: "SR$", '
'numeric_code: "968", '
'decimal_places: "2", '
'decimal_sign: ",", '
'grouping_places: "3", '
'grouping_sign: ".", '
'convertion: "", '
'international: False)')
assert suriname_dollar.__str__() == '$ 0,14'
def test_suriname_dollar_negative(self):
"""test_suriname_dollar_negative."""
amount = -100
suriname_dollar = SurinameDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert suriname_dollar.numeric_code == '968'
assert suriname_dollar.alpha_code == 'SRD'
assert suriname_dollar.decimal_places == 2
assert suriname_dollar.decimal_sign == ','
assert suriname_dollar.grouping_places == 3
assert suriname_dollar.grouping_sign == '.'
assert not suriname_dollar.international
assert suriname_dollar.symbol == '$'
assert suriname_dollar.symbol_ahead
assert suriname_dollar.symbol_separator == '\u00A0'
assert suriname_dollar.localized_symbol == 'SR$'
assert suriname_dollar.convertion == ''
assert suriname_dollar.__hash__() == hash(
(suriname_dollar.__class__, decimal, 'SRD', '968'))
assert suriname_dollar.__repr__() == (
'SurinameDollar(amount: -100, '
'alpha_code: "SRD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "\u00A0", '
'localized_symbol: "SR$", '
'numeric_code: "968", '
'decimal_places: "2", '
'decimal_sign: ",", '
'grouping_places: "3", '
'grouping_sign: ".", '
'convertion: "", '
'international: False)')
assert suriname_dollar.__str__() == '$ -100,00'
def test_suriname_dollar_custom(self):
"""test_suriname_dollar_custom."""
amount = 1000
suriname_dollar = SurinameDollar(
amount=amount,
decimal_places=5,
decimal_sign='.',
grouping_places=2,
grouping_sign=',',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert suriname_dollar.amount == decimal
assert suriname_dollar.numeric_code == '968'
assert suriname_dollar.alpha_code == 'SRD'
assert suriname_dollar.decimal_places == 5
assert suriname_dollar.decimal_sign == '.'
assert suriname_dollar.grouping_places == 2
assert suriname_dollar.grouping_sign == ','
assert suriname_dollar.international
assert suriname_dollar.symbol == '$'
assert not suriname_dollar.symbol_ahead
assert suriname_dollar.symbol_separator == '_'
assert suriname_dollar.localized_symbol == 'SR$'
assert suriname_dollar.convertion == ''
assert suriname_dollar.__hash__() == hash(
(suriname_dollar.__class__, decimal, 'SRD', '968'))
assert suriname_dollar.__repr__() == (
'SurinameDollar(amount: 1000, '
'alpha_code: "SRD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "SR$", '
'numeric_code: "968", '
'decimal_places: "5", '
'decimal_sign: ".", '
'grouping_places: "2", '
'grouping_sign: ",", '
'convertion: "", '
'international: True)')
assert suriname_dollar.__str__() == 'SRD 10,00.00000'
def test_suriname_dollar_changed(self):
"""test_csuriname_dollar_changed."""
suriname_dollar = SurinameDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
suriname_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
suriname_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
suriname_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
suriname_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
suriname_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
suriname_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
suriname_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
suriname_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
suriname_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
suriname_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
suriname_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
suriname_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
suriname_dollar.international = True
def test_suriname_dollar_math_add(self):
"""test_suriname_dollar_math_add."""
suriname_dollar_one = SurinameDollar(amount=1)
suriname_dollar_two = SurinameDollar(amount=2)
suriname_dollar_three = SurinameDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency SRD and OTHER.'):
_ = suriname_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.SurinameDollar\'> '
'and <class \'str\'>.')):
_ = suriname_dollar_one.__add__('1.00')
assert (
suriname_dollar_one +
suriname_dollar_two) == suriname_dollar_three
def test_suriname_dollar_slots(self):
"""test_suriname_dollar_slots."""
suriname_dollar = SurinameDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'SurinameDollar\' '
'object has no attribute \'new_variable\'')):
suriname_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Trinidad and Tobago Dollar representation."""
from multicurrency import TrinidadandTobagoDollar
class TestTrinidadandTobagoDollar:
"""TrinidadandTobagoDollar currency tests."""
def test_trinidad_and_tobago_dollar(self):
"""test_trinidad_and_tobago_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
trinidad_and_tobago_dollar = TrinidadandTobagoDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert trinidad_and_tobago_dollar.amount == decimal
assert trinidad_and_tobago_dollar.numeric_code == '780'
assert trinidad_and_tobago_dollar.alpha_code == 'TTD'
assert trinidad_and_tobago_dollar.decimal_places == 2
assert trinidad_and_tobago_dollar.decimal_sign == '.'
assert trinidad_and_tobago_dollar.grouping_places == 3
assert trinidad_and_tobago_dollar.grouping_sign == ','
assert not trinidad_and_tobago_dollar.international
assert trinidad_and_tobago_dollar.symbol == '$'
assert trinidad_and_tobago_dollar.symbol_ahead
assert trinidad_and_tobago_dollar.symbol_separator == ''
assert trinidad_and_tobago_dollar.localized_symbol == 'TT$'
assert trinidad_and_tobago_dollar.convertion == ''
assert trinidad_and_tobago_dollar.__hash__() == hash(
(trinidad_and_tobago_dollar.__class__, decimal, 'TTD', '780'))
assert trinidad_and_tobago_dollar.__repr__() == (
'TrinidadandTobagoDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "TTD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "TT$", '
'numeric_code: "780", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert trinidad_and_tobago_dollar.__str__() == '$0.14'
def test_trinidad_and_tobago_dollar_negative(self):
"""test_trinidad_and_tobago_dollar_negative."""
amount = -100
trinidad_and_tobago_dollar = TrinidadandTobagoDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert trinidad_and_tobago_dollar.numeric_code == '780'
assert trinidad_and_tobago_dollar.alpha_code == 'TTD'
assert trinidad_and_tobago_dollar.decimal_places == 2
assert trinidad_and_tobago_dollar.decimal_sign == '.'
assert trinidad_and_tobago_dollar.grouping_places == 3
assert trinidad_and_tobago_dollar.grouping_sign == ','
assert not trinidad_and_tobago_dollar.international
assert trinidad_and_tobago_dollar.symbol == '$'
assert trinidad_and_tobago_dollar.symbol_ahead
assert trinidad_and_tobago_dollar.symbol_separator == ''
assert trinidad_and_tobago_dollar.localized_symbol == 'TT$'
assert trinidad_and_tobago_dollar.convertion == ''
assert trinidad_and_tobago_dollar.__hash__() == hash(
(trinidad_and_tobago_dollar.__class__, decimal, 'TTD', '780'))
assert trinidad_and_tobago_dollar.__repr__() == (
'TrinidadandTobagoDollar(amount: -100, '
'alpha_code: "TTD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "TT$", '
'numeric_code: "780", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert trinidad_and_tobago_dollar.__str__() == '$-100.00'
def test_trinidad_and_tobago_dollar_custom(self):
"""test_trinidad_and_tobago_dollar_custom."""
amount = 1000
trinidad_and_tobago_dollar = TrinidadandTobagoDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert trinidad_and_tobago_dollar.amount == decimal
assert trinidad_and_tobago_dollar.numeric_code == '780'
assert trinidad_and_tobago_dollar.alpha_code == 'TTD'
assert trinidad_and_tobago_dollar.decimal_places == 5
assert trinidad_and_tobago_dollar.decimal_sign == ','
assert trinidad_and_tobago_dollar.grouping_places == 2
assert trinidad_and_tobago_dollar.grouping_sign == '.'
assert trinidad_and_tobago_dollar.international
assert trinidad_and_tobago_dollar.symbol == '$'
assert not trinidad_and_tobago_dollar.symbol_ahead
assert trinidad_and_tobago_dollar.symbol_separator == '_'
assert trinidad_and_tobago_dollar.localized_symbol == 'TT$'
assert trinidad_and_tobago_dollar.convertion == ''
assert trinidad_and_tobago_dollar.__hash__() == hash(
(trinidad_and_tobago_dollar.__class__, decimal, 'TTD', '780'))
assert trinidad_and_tobago_dollar.__repr__() == (
'TrinidadandTobagoDollar(amount: 1000, '
'alpha_code: "TTD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "TT$", '
'numeric_code: "780", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert trinidad_and_tobago_dollar.__str__() == 'TTD 10,00.00000'
def test_trinidad_and_tobago_dollar_changed(self):
"""test_ctrinidad_and_tobago_dollar_changed."""
trinidad_and_tobago_dollar = TrinidadandTobagoDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
trinidad_and_tobago_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
trinidad_and_tobago_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
trinidad_and_tobago_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
trinidad_and_tobago_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
trinidad_and_tobago_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
trinidad_and_tobago_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
trinidad_and_tobago_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
trinidad_and_tobago_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
trinidad_and_tobago_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
trinidad_and_tobago_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
trinidad_and_tobago_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
trinidad_and_tobago_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
trinidad_and_tobago_dollar.international = True
def test_trinidad_and_tobago_dollar_math_add(self):
"""test_trinidad_and_tobago_dollar_math_add."""
trinidad_and_tobago_dollar_one = TrinidadandTobagoDollar(amount=1)
trinidad_and_tobago_dollar_two = TrinidadandTobagoDollar(amount=2)
trinidad_and_tobago_dollar_three = TrinidadandTobagoDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency TTD and OTHER.'):
_ = trinidad_and_tobago_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.TrinidadandTobagoDollar\'> '
'and <class \'str\'>.')):
_ = trinidad_and_tobago_dollar_one.__add__('1.00')
assert (
trinidad_and_tobago_dollar_one +
trinidad_and_tobago_dollar_two) == trinidad_and_tobago_dollar_three
def test_trinidad_and_tobago_dollar_slots(self):
"""test_trinidad_and_tobago_dollar_slots."""
trinidad_and_tobago_dollar = TrinidadandTobagoDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'TrinidadandTobagoDollar\' '
'object has no attribute \'new_variable\'')):
trinidad_and_tobago_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Taiwan Dollar representation."""
from multicurrency import TaiwanDollar
class TestTaiwanDollar:
"""TaiwanDollar currency tests."""
def test_taiwan_dollar(self):
"""test_taiwan_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
taiwan_dollar = TaiwanDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert taiwan_dollar.amount == decimal
assert taiwan_dollar.numeric_code == '901'
assert taiwan_dollar.alpha_code == 'TWD'
assert taiwan_dollar.decimal_places == 2
assert taiwan_dollar.decimal_sign == '.'
assert taiwan_dollar.grouping_places == 3
assert taiwan_dollar.grouping_sign == ','
assert not taiwan_dollar.international
assert taiwan_dollar.symbol == '$'
assert taiwan_dollar.symbol_ahead
assert taiwan_dollar.symbol_separator == ''
assert taiwan_dollar.localized_symbol == 'TW$'
assert taiwan_dollar.convertion == ''
assert taiwan_dollar.__hash__() == hash(
(taiwan_dollar.__class__, decimal, 'TWD', '901'))
assert taiwan_dollar.__repr__() == (
'TaiwanDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "TWD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "TW$", '
'numeric_code: "901", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert taiwan_dollar.__str__() == '$0.14'
def test_taiwan_dollar_negative(self):
"""test_taiwan_dollar_negative."""
amount = -100
taiwan_dollar = TaiwanDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert taiwan_dollar.numeric_code == '901'
assert taiwan_dollar.alpha_code == 'TWD'
assert taiwan_dollar.decimal_places == 2
assert taiwan_dollar.decimal_sign == '.'
assert taiwan_dollar.grouping_places == 3
assert taiwan_dollar.grouping_sign == ','
assert not taiwan_dollar.international
assert taiwan_dollar.symbol == '$'
assert taiwan_dollar.symbol_ahead
assert taiwan_dollar.symbol_separator == ''
assert taiwan_dollar.localized_symbol == 'TW$'
assert taiwan_dollar.convertion == ''
assert taiwan_dollar.__hash__() == hash(
(taiwan_dollar.__class__, decimal, 'TWD', '901'))
assert taiwan_dollar.__repr__() == (
'TaiwanDollar(amount: -100, '
'alpha_code: "TWD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "TW$", '
'numeric_code: "901", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert taiwan_dollar.__str__() == '$-100.00'
def test_taiwan_dollar_custom(self):
"""test_taiwan_dollar_custom."""
amount = 1000
taiwan_dollar = TaiwanDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert taiwan_dollar.amount == decimal
assert taiwan_dollar.numeric_code == '901'
assert taiwan_dollar.alpha_code == 'TWD'
assert taiwan_dollar.decimal_places == 5
assert taiwan_dollar.decimal_sign == ','
assert taiwan_dollar.grouping_places == 2
assert taiwan_dollar.grouping_sign == '.'
assert taiwan_dollar.international
assert taiwan_dollar.symbol == '$'
assert not taiwan_dollar.symbol_ahead
assert taiwan_dollar.symbol_separator == '_'
assert taiwan_dollar.localized_symbol == 'TW$'
assert taiwan_dollar.convertion == ''
assert taiwan_dollar.__hash__() == hash(
(taiwan_dollar.__class__, decimal, 'TWD', '901'))
assert taiwan_dollar.__repr__() == (
'TaiwanDollar(amount: 1000, '
'alpha_code: "TWD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "TW$", '
'numeric_code: "901", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert taiwan_dollar.__str__() == 'TWD 10,00.00000'
def test_taiwan_dollar_changed(self):
"""test_ctaiwan_dollar_changed."""
taiwan_dollar = TaiwanDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
taiwan_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
taiwan_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
taiwan_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
taiwan_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
taiwan_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
taiwan_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
taiwan_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
taiwan_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
taiwan_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
taiwan_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
taiwan_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
taiwan_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
taiwan_dollar.international = True
def test_taiwan_dollar_math_add(self):
"""test_taiwan_dollar_math_add."""
taiwan_dollar_one = TaiwanDollar(amount=1)
taiwan_dollar_two = TaiwanDollar(amount=2)
taiwan_dollar_three = TaiwanDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency TWD and OTHER.'):
_ = taiwan_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.TaiwanDollar\'> '
'and <class \'str\'>.')):
_ = taiwan_dollar_one.__add__('1.00')
assert (
taiwan_dollar_one +
taiwan_dollar_two) == taiwan_dollar_three
def test_taiwan_dollar_slots(self):
"""test_taiwan_dollar_slots."""
taiwan_dollar = TaiwanDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'TaiwanDollar\' '
'object has no attribute \'new_variable\'')):
taiwan_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the US Dollar representation."""
from multicurrency import USDollar
class TestUSDollar:
"""USDollar currency tests."""
def test_us_dollar(self):
"""test_us_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
us_dollar = USDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar.amount == decimal
assert us_dollar.numeric_code == '840'
assert us_dollar.alpha_code == 'USD'
assert us_dollar.decimal_places == 2
assert us_dollar.decimal_sign == '.'
assert us_dollar.grouping_places == 3
assert us_dollar.grouping_sign == ','
assert not us_dollar.international
assert us_dollar.symbol == '$'
assert us_dollar.symbol_ahead
assert us_dollar.symbol_separator == ''
assert us_dollar.localized_symbol == 'US$'
assert us_dollar.convertion == ''
assert us_dollar.__hash__() == hash(
(us_dollar.__class__, decimal, 'USD', '840'))
assert us_dollar.__repr__() == (
'USDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "US$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar.__str__() == '$0.14'
def test_us_dollar_negative(self):
"""test_us_dollar_negative."""
amount = -100
us_dollar = USDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar.numeric_code == '840'
assert us_dollar.alpha_code == 'USD'
assert us_dollar.decimal_places == 2
assert us_dollar.decimal_sign == '.'
assert us_dollar.grouping_places == 3
assert us_dollar.grouping_sign == ','
assert not us_dollar.international
assert us_dollar.symbol == '$'
assert us_dollar.symbol_ahead
assert us_dollar.symbol_separator == ''
assert us_dollar.localized_symbol == 'US$'
assert us_dollar.convertion == ''
assert us_dollar.__hash__() == hash(
(us_dollar.__class__, decimal, 'USD', '840'))
assert us_dollar.__repr__() == (
'USDollar(amount: -100, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "US$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar.__str__() == '$-100.00'
def test_us_dollar_custom(self):
"""test_us_dollar_custom."""
amount = 1000
us_dollar = USDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert us_dollar.amount == decimal
assert us_dollar.numeric_code == '840'
assert us_dollar.alpha_code == 'USD'
assert us_dollar.decimal_places == 5
assert us_dollar.decimal_sign == ','
assert us_dollar.grouping_places == 2
assert us_dollar.grouping_sign == '.'
assert us_dollar.international
assert us_dollar.symbol == '$'
assert not us_dollar.symbol_ahead
assert us_dollar.symbol_separator == '_'
assert us_dollar.localized_symbol == 'US$'
assert us_dollar.convertion == ''
assert us_dollar.__hash__() == hash(
(us_dollar.__class__, decimal, 'USD', '840'))
assert us_dollar.__repr__() == (
'USDollar(amount: 1000, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "US$", '
'numeric_code: "840", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert us_dollar.__str__() == 'USD 10,00.00000'
def test_us_dollar_changed(self):
"""test_cus_dollar_changed."""
us_dollar = USDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar.international = True
def test_us_dollar_math_add(self):
"""test_us_dollar_math_add."""
us_dollar_one = USDollar(amount=1)
us_dollar_two = USDollar(amount=2)
us_dollar_three = USDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency USD and OTHER.'):
_ = us_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.USDollar\'> '
'and <class \'str\'>.')):
_ = us_dollar_one.__add__('1.00')
assert (
us_dollar_one +
us_dollar_two) == us_dollar_three
def test_us_dollar_slots(self):
"""test_us_dollar_slots."""
us_dollar = USDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'USDollar\' '
'object has no attribute \'new_variable\'')):
us_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the US Dollar AS representation."""
from multicurrency import USDollarAS
class TestUSDollarAS:
"""USDollarAS currency tests."""
def test_us_dollar_as(self):
"""test_us_dollar_as."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
us_dollar_as = USDollarAS(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_as.amount == decimal
assert us_dollar_as.numeric_code == '840'
assert us_dollar_as.alpha_code == 'USD'
assert us_dollar_as.decimal_places == 2
assert us_dollar_as.decimal_sign == '.'
assert us_dollar_as.grouping_places == 3
assert us_dollar_as.grouping_sign == ','
assert not us_dollar_as.international
assert us_dollar_as.symbol == '$'
assert us_dollar_as.symbol_ahead
assert us_dollar_as.symbol_separator == ''
assert us_dollar_as.localized_symbol == 'AS$'
assert us_dollar_as.convertion == ''
assert us_dollar_as.__hash__() == hash(
(us_dollar_as.__class__, decimal, 'USD', '840'))
assert us_dollar_as.__repr__() == (
'USDollarAS(amount: 0.1428571428571428571428571429, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "AS$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_as.__str__() == '$0.14'
def test_us_dollar_as_negative(self):
"""test_us_dollar_as_negative."""
amount = -100
us_dollar_as = USDollarAS(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_as.numeric_code == '840'
assert us_dollar_as.alpha_code == 'USD'
assert us_dollar_as.decimal_places == 2
assert us_dollar_as.decimal_sign == '.'
assert us_dollar_as.grouping_places == 3
assert us_dollar_as.grouping_sign == ','
assert not us_dollar_as.international
assert us_dollar_as.symbol == '$'
assert us_dollar_as.symbol_ahead
assert us_dollar_as.symbol_separator == ''
assert us_dollar_as.localized_symbol == 'AS$'
assert us_dollar_as.convertion == ''
assert us_dollar_as.__hash__() == hash(
(us_dollar_as.__class__, decimal, 'USD', '840'))
assert us_dollar_as.__repr__() == (
'USDollarAS(amount: -100, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "AS$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_as.__str__() == '$-100.00'
def test_us_dollar_as_custom(self):
"""test_us_dollar_as_custom."""
amount = 1000
us_dollar_as = USDollarAS(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_as.amount == decimal
assert us_dollar_as.numeric_code == '840'
assert us_dollar_as.alpha_code == 'USD'
assert us_dollar_as.decimal_places == 5
assert us_dollar_as.decimal_sign == ','
assert us_dollar_as.grouping_places == 2
assert us_dollar_as.grouping_sign == '.'
assert us_dollar_as.international
assert us_dollar_as.symbol == '$'
assert not us_dollar_as.symbol_ahead
assert us_dollar_as.symbol_separator == '_'
assert us_dollar_as.localized_symbol == 'AS$'
assert us_dollar_as.convertion == ''
assert us_dollar_as.__hash__() == hash(
(us_dollar_as.__class__, decimal, 'USD', '840'))
assert us_dollar_as.__repr__() == (
'USDollarAS(amount: 1000, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "AS$", '
'numeric_code: "840", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert us_dollar_as.__str__() == 'USD 10,00.00000'
def test_us_dollar_as_changed(self):
"""test_cus_dollar_as_changed."""
us_dollar_as = USDollarAS(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_as.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_as.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_as.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_as.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_as.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_as.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_as.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_as.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_as.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_as.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_as.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_as.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_as.international = True
def test_us_dollar_as_math_add(self):
"""test_us_dollar_as_math_add."""
us_dollar_as_one = USDollarAS(amount=1)
us_dollar_as_two = USDollarAS(amount=2)
us_dollar_as_three = USDollarAS(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency USD and OTHER.'):
_ = us_dollar_as_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.USDollarAS\'> '
'and <class \'str\'>.')):
_ = us_dollar_as_one.__add__('1.00')
assert (
us_dollar_as_one +
us_dollar_as_two) == us_dollar_as_three
def test_us_dollar_as_slots(self):
"""test_us_dollar_as_slots."""
us_dollar_as = USDollarAS(amount=1000)
with raises(
AttributeError,
match=(
'\'USDollarAS\' '
'object has no attribute \'new_variable\'')):
us_dollar_as.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the US Dollar IO representation."""
from multicurrency import USDollarIO
class TestUSDollarIO:
"""USDollarIO currency tests."""
def test_us_dollar_io(self):
"""test_us_dollar_io."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
us_dollar_io = USDollarIO(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_io.amount == decimal
assert us_dollar_io.numeric_code == '840'
assert us_dollar_io.alpha_code == 'USD'
assert us_dollar_io.decimal_places == 2
assert us_dollar_io.decimal_sign == '.'
assert us_dollar_io.grouping_places == 3
assert us_dollar_io.grouping_sign == ','
assert not us_dollar_io.international
assert us_dollar_io.symbol == '$'
assert us_dollar_io.symbol_ahead
assert us_dollar_io.symbol_separator == ''
assert us_dollar_io.localized_symbol == 'IO$'
assert us_dollar_io.convertion == ''
assert us_dollar_io.__hash__() == hash(
(us_dollar_io.__class__, decimal, 'USD', '840'))
assert us_dollar_io.__repr__() == (
'USDollarIO(amount: 0.1428571428571428571428571429, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "IO$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_io.__str__() == '$0.14'
def test_us_dollar_io_negative(self):
"""test_us_dollar_io_negative."""
amount = -100
us_dollar_io = USDollarIO(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_io.numeric_code == '840'
assert us_dollar_io.alpha_code == 'USD'
assert us_dollar_io.decimal_places == 2
assert us_dollar_io.decimal_sign == '.'
assert us_dollar_io.grouping_places == 3
assert us_dollar_io.grouping_sign == ','
assert not us_dollar_io.international
assert us_dollar_io.symbol == '$'
assert us_dollar_io.symbol_ahead
assert us_dollar_io.symbol_separator == ''
assert us_dollar_io.localized_symbol == 'IO$'
assert us_dollar_io.convertion == ''
assert us_dollar_io.__hash__() == hash(
(us_dollar_io.__class__, decimal, 'USD', '840'))
assert us_dollar_io.__repr__() == (
'USDollarIO(amount: -100, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "IO$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_io.__str__() == '$-100.00'
def test_us_dollar_io_custom(self):
"""test_us_dollar_io_custom."""
amount = 1000
us_dollar_io = USDollarIO(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_io.amount == decimal
assert us_dollar_io.numeric_code == '840'
assert us_dollar_io.alpha_code == 'USD'
assert us_dollar_io.decimal_places == 5
assert us_dollar_io.decimal_sign == ','
assert us_dollar_io.grouping_places == 2
assert us_dollar_io.grouping_sign == '.'
assert us_dollar_io.international
assert us_dollar_io.symbol == '$'
assert not us_dollar_io.symbol_ahead
assert us_dollar_io.symbol_separator == '_'
assert us_dollar_io.localized_symbol == 'IO$'
assert us_dollar_io.convertion == ''
assert us_dollar_io.__hash__() == hash(
(us_dollar_io.__class__, decimal, 'USD', '840'))
assert us_dollar_io.__repr__() == (
'USDollarIO(amount: 1000, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "IO$", '
'numeric_code: "840", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert us_dollar_io.__str__() == 'USD 10,00.00000'
def test_us_dollar_io_changed(self):
"""test_cus_dollar_io_changed."""
us_dollar_io = USDollarIO(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_io.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_io.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_io.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_io.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_io.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_io.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_io.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_io.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_io.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_io.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_io.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_io.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_io.international = True
def test_us_dollar_io_math_add(self):
"""test_us_dollar_io_math_add."""
us_dollar_io_one = USDollarIO(amount=1)
us_dollar_io_two = USDollarIO(amount=2)
us_dollar_io_three = USDollarIO(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency USD and OTHER.'):
_ = us_dollar_io_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.USDollarIO\'> '
'and <class \'str\'>.')):
_ = us_dollar_io_one.__add__('1.00')
assert (
us_dollar_io_one +
us_dollar_io_two) == us_dollar_io_three
def test_us_dollar_io_slots(self):
"""test_us_dollar_io_slots."""
us_dollar_io = USDollarIO(amount=1000)
with raises(
AttributeError,
match=(
'\'USDollarIO\' '
'object has no attribute \'new_variable\'')):
us_dollar_io.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the US Dollar VG representation."""
from multicurrency import USDollarVG
class TestUSDollarVG:
"""USDollarVG currency tests."""
def test_us_dollar_vg(self):
"""test_us_dollar_vg."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
us_dollar_vg = USDollarVG(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_vg.amount == decimal
assert us_dollar_vg.numeric_code == '840'
assert us_dollar_vg.alpha_code == 'USD'
assert us_dollar_vg.decimal_places == 2
assert us_dollar_vg.decimal_sign == '.'
assert us_dollar_vg.grouping_places == 3
assert us_dollar_vg.grouping_sign == ','
assert not us_dollar_vg.international
assert us_dollar_vg.symbol == '$'
assert us_dollar_vg.symbol_ahead
assert us_dollar_vg.symbol_separator == ''
assert us_dollar_vg.localized_symbol == 'VG$'
assert us_dollar_vg.convertion == ''
assert us_dollar_vg.__hash__() == hash(
(us_dollar_vg.__class__, decimal, 'USD', '840'))
assert us_dollar_vg.__repr__() == (
'USDollarVG(amount: 0.1428571428571428571428571429, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "VG$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_vg.__str__() == '$0.14'
def test_us_dollar_vg_negative(self):
"""test_us_dollar_vg_negative."""
amount = -100
us_dollar_vg = USDollarVG(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_vg.numeric_code == '840'
assert us_dollar_vg.alpha_code == 'USD'
assert us_dollar_vg.decimal_places == 2
assert us_dollar_vg.decimal_sign == '.'
assert us_dollar_vg.grouping_places == 3
assert us_dollar_vg.grouping_sign == ','
assert not us_dollar_vg.international
assert us_dollar_vg.symbol == '$'
assert us_dollar_vg.symbol_ahead
assert us_dollar_vg.symbol_separator == ''
assert us_dollar_vg.localized_symbol == 'VG$'
assert us_dollar_vg.convertion == ''
assert us_dollar_vg.__hash__() == hash(
(us_dollar_vg.__class__, decimal, 'USD', '840'))
assert us_dollar_vg.__repr__() == (
'USDollarVG(amount: -100, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "VG$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_vg.__str__() == '$-100.00'
def test_us_dollar_vg_custom(self):
"""test_us_dollar_vg_custom."""
amount = 1000
us_dollar_vg = USDollarVG(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_vg.amount == decimal
assert us_dollar_vg.numeric_code == '840'
assert us_dollar_vg.alpha_code == 'USD'
assert us_dollar_vg.decimal_places == 5
assert us_dollar_vg.decimal_sign == ','
assert us_dollar_vg.grouping_places == 2
assert us_dollar_vg.grouping_sign == '.'
assert us_dollar_vg.international
assert us_dollar_vg.symbol == '$'
assert not us_dollar_vg.symbol_ahead
assert us_dollar_vg.symbol_separator == '_'
assert us_dollar_vg.localized_symbol == 'VG$'
assert us_dollar_vg.convertion == ''
assert us_dollar_vg.__hash__() == hash(
(us_dollar_vg.__class__, decimal, 'USD', '840'))
assert us_dollar_vg.__repr__() == (
'USDollarVG(amount: 1000, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "VG$", '
'numeric_code: "840", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert us_dollar_vg.__str__() == 'USD 10,00.00000'
def test_us_dollar_vg_changed(self):
"""test_cus_dollar_vg_changed."""
us_dollar_vg = USDollarVG(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vg.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vg.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vg.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vg.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vg.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vg.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vg.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vg.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vg.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vg.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vg.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vg.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vg.international = True
def test_us_dollar_vg_math_add(self):
"""test_us_dollar_vg_math_add."""
us_dollar_vg_one = USDollarVG(amount=1)
us_dollar_vg_two = USDollarVG(amount=2)
us_dollar_vg_three = USDollarVG(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency USD and OTHER.'):
_ = us_dollar_vg_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.USDollarVG\'> '
'and <class \'str\'>.')):
_ = us_dollar_vg_one.__add__('1.00')
assert (
us_dollar_vg_one +
us_dollar_vg_two) == us_dollar_vg_three
def test_us_dollar_vg_slots(self):
"""test_us_dollar_vg_slots."""
us_dollar_vg = USDollarVG(amount=1000)
with raises(
AttributeError,
match=(
'\'USDollarVG\' '
'object has no attribute \'new_variable\'')):
us_dollar_vg.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the US Dollar GU representation."""
from multicurrency import USDollarGU
class TestUSDollarGU:
"""USDollarGU currency tests."""
def test_us_dollar_gu(self):
"""test_us_dollar_gu."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
us_dollar_gu = USDollarGU(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_gu.amount == decimal
assert us_dollar_gu.numeric_code == '840'
assert us_dollar_gu.alpha_code == 'USD'
assert us_dollar_gu.decimal_places == 2
assert us_dollar_gu.decimal_sign == '.'
assert us_dollar_gu.grouping_places == 3
assert us_dollar_gu.grouping_sign == ','
assert not us_dollar_gu.international
assert us_dollar_gu.symbol == '$'
assert us_dollar_gu.symbol_ahead
assert us_dollar_gu.symbol_separator == ''
assert us_dollar_gu.localized_symbol == 'GU$'
assert us_dollar_gu.convertion == ''
assert us_dollar_gu.__hash__() == hash(
(us_dollar_gu.__class__, decimal, 'USD', '840'))
assert us_dollar_gu.__repr__() == (
'USDollarGU(amount: 0.1428571428571428571428571429, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "GU$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_gu.__str__() == '$0.14'
def test_us_dollar_gu_negative(self):
"""test_us_dollar_gu_negative."""
amount = -100
us_dollar_gu = USDollarGU(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_gu.numeric_code == '840'
assert us_dollar_gu.alpha_code == 'USD'
assert us_dollar_gu.decimal_places == 2
assert us_dollar_gu.decimal_sign == '.'
assert us_dollar_gu.grouping_places == 3
assert us_dollar_gu.grouping_sign == ','
assert not us_dollar_gu.international
assert us_dollar_gu.symbol == '$'
assert us_dollar_gu.symbol_ahead
assert us_dollar_gu.symbol_separator == ''
assert us_dollar_gu.localized_symbol == 'GU$'
assert us_dollar_gu.convertion == ''
assert us_dollar_gu.__hash__() == hash(
(us_dollar_gu.__class__, decimal, 'USD', '840'))
assert us_dollar_gu.__repr__() == (
'USDollarGU(amount: -100, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "GU$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_gu.__str__() == '$-100.00'
def test_us_dollar_gu_custom(self):
"""test_us_dollar_gu_custom."""
amount = 1000
us_dollar_gu = USDollarGU(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_gu.amount == decimal
assert us_dollar_gu.numeric_code == '840'
assert us_dollar_gu.alpha_code == 'USD'
assert us_dollar_gu.decimal_places == 5
assert us_dollar_gu.decimal_sign == ','
assert us_dollar_gu.grouping_places == 2
assert us_dollar_gu.grouping_sign == '.'
assert us_dollar_gu.international
assert us_dollar_gu.symbol == '$'
assert not us_dollar_gu.symbol_ahead
assert us_dollar_gu.symbol_separator == '_'
assert us_dollar_gu.localized_symbol == 'GU$'
assert us_dollar_gu.convertion == ''
assert us_dollar_gu.__hash__() == hash(
(us_dollar_gu.__class__, decimal, 'USD', '840'))
assert us_dollar_gu.__repr__() == (
'USDollarGU(amount: 1000, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "GU$", '
'numeric_code: "840", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert us_dollar_gu.__str__() == 'USD 10,00.00000'
def test_us_dollar_gu_changed(self):
"""test_cus_dollar_gu_changed."""
us_dollar_gu = USDollarGU(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_gu.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_gu.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_gu.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_gu.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_gu.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_gu.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_gu.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_gu.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_gu.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_gu.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_gu.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_gu.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_gu.international = True
def test_us_dollar_gu_math_add(self):
"""test_us_dollar_gu_math_add."""
us_dollar_gu_one = USDollarGU(amount=1)
us_dollar_gu_two = USDollarGU(amount=2)
us_dollar_gu_three = USDollarGU(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency USD and OTHER.'):
_ = us_dollar_gu_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.USDollarGU\'> '
'and <class \'str\'>.')):
_ = us_dollar_gu_one.__add__('1.00')
assert (
us_dollar_gu_one +
us_dollar_gu_two) == us_dollar_gu_three
def test_us_dollar_gu_slots(self):
"""test_us_dollar_gu_slots."""
us_dollar_gu = USDollarGU(amount=1000)
with raises(
AttributeError,
match=(
'\'USDollarGU\' '
'object has no attribute \'new_variable\'')):
us_dollar_gu.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the US Dollar HT representation."""
from multicurrency import USDollarHT
class TestUSDollarHT:
"""USDollarHT currency tests."""
def test_us_dollar_ht(self):
"""test_us_dollar_ht."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
us_dollar_ht = USDollarHT(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_ht.amount == decimal
assert us_dollar_ht.numeric_code == '840'
assert us_dollar_ht.alpha_code == 'USD'
assert us_dollar_ht.decimal_places == 2
assert us_dollar_ht.decimal_sign == '.'
assert us_dollar_ht.grouping_places == 3
assert us_dollar_ht.grouping_sign == ','
assert not us_dollar_ht.international
assert us_dollar_ht.symbol == '$'
assert us_dollar_ht.symbol_ahead
assert us_dollar_ht.symbol_separator == ''
assert us_dollar_ht.localized_symbol == 'HT$'
assert us_dollar_ht.convertion == ''
assert us_dollar_ht.__hash__() == hash(
(us_dollar_ht.__class__, decimal, 'USD', '840'))
assert us_dollar_ht.__repr__() == (
'USDollarHT(amount: 0.1428571428571428571428571429, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "HT$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_ht.__str__() == '$0.14'
def test_us_dollar_ht_negative(self):
"""test_us_dollar_ht_negative."""
amount = -100
us_dollar_ht = USDollarHT(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_ht.numeric_code == '840'
assert us_dollar_ht.alpha_code == 'USD'
assert us_dollar_ht.decimal_places == 2
assert us_dollar_ht.decimal_sign == '.'
assert us_dollar_ht.grouping_places == 3
assert us_dollar_ht.grouping_sign == ','
assert not us_dollar_ht.international
assert us_dollar_ht.symbol == '$'
assert us_dollar_ht.symbol_ahead
assert us_dollar_ht.symbol_separator == ''
assert us_dollar_ht.localized_symbol == 'HT$'
assert us_dollar_ht.convertion == ''
assert us_dollar_ht.__hash__() == hash(
(us_dollar_ht.__class__, decimal, 'USD', '840'))
assert us_dollar_ht.__repr__() == (
'USDollarHT(amount: -100, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "HT$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_ht.__str__() == '$-100.00'
def test_us_dollar_ht_custom(self):
"""test_us_dollar_ht_custom."""
amount = 1000
us_dollar_ht = USDollarHT(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_ht.amount == decimal
assert us_dollar_ht.numeric_code == '840'
assert us_dollar_ht.alpha_code == 'USD'
assert us_dollar_ht.decimal_places == 5
assert us_dollar_ht.decimal_sign == ','
assert us_dollar_ht.grouping_places == 2
assert us_dollar_ht.grouping_sign == '.'
assert us_dollar_ht.international
assert us_dollar_ht.symbol == '$'
assert not us_dollar_ht.symbol_ahead
assert us_dollar_ht.symbol_separator == '_'
assert us_dollar_ht.localized_symbol == 'HT$'
assert us_dollar_ht.convertion == ''
assert us_dollar_ht.__hash__() == hash(
(us_dollar_ht.__class__, decimal, 'USD', '840'))
assert us_dollar_ht.__repr__() == (
'USDollarHT(amount: 1000, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "HT$", '
'numeric_code: "840", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert us_dollar_ht.__str__() == 'USD 10,00.00000'
def test_us_dollar_ht_changed(self):
"""test_cus_dollar_ht_changed."""
us_dollar_ht = USDollarHT(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_ht.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_ht.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_ht.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_ht.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_ht.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_ht.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_ht.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_ht.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_ht.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_ht.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_ht.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_ht.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_ht.international = True
def test_us_dollar_ht_math_add(self):
"""test_us_dollar_ht_math_add."""
us_dollar_ht_one = USDollarHT(amount=1)
us_dollar_ht_two = USDollarHT(amount=2)
us_dollar_ht_three = USDollarHT(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency USD and OTHER.'):
_ = us_dollar_ht_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.USDollarHT\'> '
'and <class \'str\'>.')):
_ = us_dollar_ht_one.__add__('1.00')
assert (
us_dollar_ht_one +
us_dollar_ht_two) == us_dollar_ht_three
def test_us_dollar_ht_slots(self):
"""test_us_dollar_ht_slots."""
us_dollar_ht = USDollarHT(amount=1000)
with raises(
AttributeError,
match=(
'\'USDollarHT\' '
'object has no attribute \'new_variable\'')):
us_dollar_ht.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the US Dollar MH representation."""
from multicurrency import USDollarMH
class TestUSDollarMH:
"""USDollarMH currency tests."""
def test_us_dollar_mh(self):
"""test_us_dollar_mh."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
us_dollar_mh = USDollarMH(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_mh.amount == decimal
assert us_dollar_mh.numeric_code == '840'
assert us_dollar_mh.alpha_code == 'USD'
assert us_dollar_mh.decimal_places == 2
assert us_dollar_mh.decimal_sign == '.'
assert us_dollar_mh.grouping_places == 3
assert us_dollar_mh.grouping_sign == ','
assert not us_dollar_mh.international
assert us_dollar_mh.symbol == '$'
assert us_dollar_mh.symbol_ahead
assert us_dollar_mh.symbol_separator == ''
assert us_dollar_mh.localized_symbol == 'MH$'
assert us_dollar_mh.convertion == ''
assert us_dollar_mh.__hash__() == hash(
(us_dollar_mh.__class__, decimal, 'USD', '840'))
assert us_dollar_mh.__repr__() == (
'USDollarMH(amount: 0.1428571428571428571428571429, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "MH$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_mh.__str__() == '$0.14'
def test_us_dollar_mh_negative(self):
"""test_us_dollar_mh_negative."""
amount = -100
us_dollar_mh = USDollarMH(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_mh.numeric_code == '840'
assert us_dollar_mh.alpha_code == 'USD'
assert us_dollar_mh.decimal_places == 2
assert us_dollar_mh.decimal_sign == '.'
assert us_dollar_mh.grouping_places == 3
assert us_dollar_mh.grouping_sign == ','
assert not us_dollar_mh.international
assert us_dollar_mh.symbol == '$'
assert us_dollar_mh.symbol_ahead
assert us_dollar_mh.symbol_separator == ''
assert us_dollar_mh.localized_symbol == 'MH$'
assert us_dollar_mh.convertion == ''
assert us_dollar_mh.__hash__() == hash(
(us_dollar_mh.__class__, decimal, 'USD', '840'))
assert us_dollar_mh.__repr__() == (
'USDollarMH(amount: -100, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "MH$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_mh.__str__() == '$-100.00'
def test_us_dollar_mh_custom(self):
"""test_us_dollar_mh_custom."""
amount = 1000
us_dollar_mh = USDollarMH(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_mh.amount == decimal
assert us_dollar_mh.numeric_code == '840'
assert us_dollar_mh.alpha_code == 'USD'
assert us_dollar_mh.decimal_places == 5
assert us_dollar_mh.decimal_sign == ','
assert us_dollar_mh.grouping_places == 2
assert us_dollar_mh.grouping_sign == '.'
assert us_dollar_mh.international
assert us_dollar_mh.symbol == '$'
assert not us_dollar_mh.symbol_ahead
assert us_dollar_mh.symbol_separator == '_'
assert us_dollar_mh.localized_symbol == 'MH$'
assert us_dollar_mh.convertion == ''
assert us_dollar_mh.__hash__() == hash(
(us_dollar_mh.__class__, decimal, 'USD', '840'))
assert us_dollar_mh.__repr__() == (
'USDollarMH(amount: 1000, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "MH$", '
'numeric_code: "840", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert us_dollar_mh.__str__() == 'USD 10,00.00000'
def test_us_dollar_mh_changed(self):
"""test_cus_dollar_mh_changed."""
us_dollar_mh = USDollarMH(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mh.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mh.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mh.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mh.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mh.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mh.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mh.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mh.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mh.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mh.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mh.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mh.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mh.international = True
def test_us_dollar_mh_math_add(self):
"""test_us_dollar_mh_math_add."""
us_dollar_mh_one = USDollarMH(amount=1)
us_dollar_mh_two = USDollarMH(amount=2)
us_dollar_mh_three = USDollarMH(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency USD and OTHER.'):
_ = us_dollar_mh_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.USDollarMH\'> '
'and <class \'str\'>.')):
_ = us_dollar_mh_one.__add__('1.00')
assert (
us_dollar_mh_one +
us_dollar_mh_two) == us_dollar_mh_three
def test_us_dollar_mh_slots(self):
"""test_us_dollar_mh_slots."""
us_dollar_mh = USDollarMH(amount=1000)
with raises(
AttributeError,
match=(
'\'USDollarMH\' '
'object has no attribute \'new_variable\'')):
us_dollar_mh.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the US Dollar FM representation."""
from multicurrency import USDollarFM
class TestUSDollarFM:
"""USDollarFM currency tests."""
def test_us_dollar_fm(self):
"""test_us_dollar_fm."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
us_dollar_fm = USDollarFM(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_fm.amount == decimal
assert us_dollar_fm.numeric_code == '840'
assert us_dollar_fm.alpha_code == 'USD'
assert us_dollar_fm.decimal_places == 2
assert us_dollar_fm.decimal_sign == '.'
assert us_dollar_fm.grouping_places == 3
assert us_dollar_fm.grouping_sign == ','
assert not us_dollar_fm.international
assert us_dollar_fm.symbol == '$'
assert us_dollar_fm.symbol_ahead
assert us_dollar_fm.symbol_separator == ''
assert us_dollar_fm.localized_symbol == 'FM$'
assert us_dollar_fm.convertion == ''
assert us_dollar_fm.__hash__() == hash(
(us_dollar_fm.__class__, decimal, 'USD', '840'))
assert us_dollar_fm.__repr__() == (
'USDollarFM(amount: 0.1428571428571428571428571429, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "FM$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_fm.__str__() == '$0.14'
def test_us_dollar_fm_negative(self):
"""test_us_dollar_fm_negative."""
amount = -100
us_dollar_fm = USDollarFM(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_fm.numeric_code == '840'
assert us_dollar_fm.alpha_code == 'USD'
assert us_dollar_fm.decimal_places == 2
assert us_dollar_fm.decimal_sign == '.'
assert us_dollar_fm.grouping_places == 3
assert us_dollar_fm.grouping_sign == ','
assert not us_dollar_fm.international
assert us_dollar_fm.symbol == '$'
assert us_dollar_fm.symbol_ahead
assert us_dollar_fm.symbol_separator == ''
assert us_dollar_fm.localized_symbol == 'FM$'
assert us_dollar_fm.convertion == ''
assert us_dollar_fm.__hash__() == hash(
(us_dollar_fm.__class__, decimal, 'USD', '840'))
assert us_dollar_fm.__repr__() == (
'USDollarFM(amount: -100, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "FM$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_fm.__str__() == '$-100.00'
def test_us_dollar_fm_custom(self):
"""test_us_dollar_fm_custom."""
amount = 1000
us_dollar_fm = USDollarFM(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_fm.amount == decimal
assert us_dollar_fm.numeric_code == '840'
assert us_dollar_fm.alpha_code == 'USD'
assert us_dollar_fm.decimal_places == 5
assert us_dollar_fm.decimal_sign == ','
assert us_dollar_fm.grouping_places == 2
assert us_dollar_fm.grouping_sign == '.'
assert us_dollar_fm.international
assert us_dollar_fm.symbol == '$'
assert not us_dollar_fm.symbol_ahead
assert us_dollar_fm.symbol_separator == '_'
assert us_dollar_fm.localized_symbol == 'FM$'
assert us_dollar_fm.convertion == ''
assert us_dollar_fm.__hash__() == hash(
(us_dollar_fm.__class__, decimal, 'USD', '840'))
assert us_dollar_fm.__repr__() == (
'USDollarFM(amount: 1000, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "FM$", '
'numeric_code: "840", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert us_dollar_fm.__str__() == 'USD 10,00.00000'
def test_us_dollar_fm_changed(self):
"""test_cus_dollar_fm_changed."""
us_dollar_fm = USDollarFM(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_fm.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_fm.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_fm.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_fm.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_fm.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_fm.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_fm.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_fm.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_fm.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_fm.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_fm.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_fm.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_fm.international = True
def test_us_dollar_fm_math_add(self):
"""test_us_dollar_fm_math_add."""
us_dollar_fm_one = USDollarFM(amount=1)
us_dollar_fm_two = USDollarFM(amount=2)
us_dollar_fm_three = USDollarFM(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency USD and OTHER.'):
_ = us_dollar_fm_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.USDollarFM\'> '
'and <class \'str\'>.')):
_ = us_dollar_fm_one.__add__('1.00')
assert (
us_dollar_fm_one +
us_dollar_fm_two) == us_dollar_fm_three
def test_us_dollar_fm_slots(self):
"""test_us_dollar_fm_slots."""
us_dollar_fm = USDollarFM(amount=1000)
with raises(
AttributeError,
match=(
'\'USDollarFM\' '
'object has no attribute \'new_variable\'')):
us_dollar_fm.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the US Dollar MP representation."""
from multicurrency import USDollarMP
class TestUSDollarMP:
"""USDollarMP currency tests."""
def test_us_dollar_mp(self):
"""test_us_dollar_mp."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
us_dollar_mp = USDollarMP(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_mp.amount == decimal
assert us_dollar_mp.numeric_code == '840'
assert us_dollar_mp.alpha_code == 'USD'
assert us_dollar_mp.decimal_places == 2
assert us_dollar_mp.decimal_sign == '.'
assert us_dollar_mp.grouping_places == 3
assert us_dollar_mp.grouping_sign == ','
assert not us_dollar_mp.international
assert us_dollar_mp.symbol == '$'
assert us_dollar_mp.symbol_ahead
assert us_dollar_mp.symbol_separator == ''
assert us_dollar_mp.localized_symbol == 'MP$'
assert us_dollar_mp.convertion == ''
assert us_dollar_mp.__hash__() == hash(
(us_dollar_mp.__class__, decimal, 'USD', '840'))
assert us_dollar_mp.__repr__() == (
'USDollarMP(amount: 0.1428571428571428571428571429, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "MP$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_mp.__str__() == '$0.14'
def test_us_dollar_mp_negative(self):
"""test_us_dollar_mp_negative."""
amount = -100
us_dollar_mp = USDollarMP(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_mp.numeric_code == '840'
assert us_dollar_mp.alpha_code == 'USD'
assert us_dollar_mp.decimal_places == 2
assert us_dollar_mp.decimal_sign == '.'
assert us_dollar_mp.grouping_places == 3
assert us_dollar_mp.grouping_sign == ','
assert not us_dollar_mp.international
assert us_dollar_mp.symbol == '$'
assert us_dollar_mp.symbol_ahead
assert us_dollar_mp.symbol_separator == ''
assert us_dollar_mp.localized_symbol == 'MP$'
assert us_dollar_mp.convertion == ''
assert us_dollar_mp.__hash__() == hash(
(us_dollar_mp.__class__, decimal, 'USD', '840'))
assert us_dollar_mp.__repr__() == (
'USDollarMP(amount: -100, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "MP$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_mp.__str__() == '$-100.00'
def test_us_dollar_mp_custom(self):
"""test_us_dollar_mp_custom."""
amount = 1000
us_dollar_mp = USDollarMP(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_mp.amount == decimal
assert us_dollar_mp.numeric_code == '840'
assert us_dollar_mp.alpha_code == 'USD'
assert us_dollar_mp.decimal_places == 5
assert us_dollar_mp.decimal_sign == ','
assert us_dollar_mp.grouping_places == 2
assert us_dollar_mp.grouping_sign == '.'
assert us_dollar_mp.international
assert us_dollar_mp.symbol == '$'
assert not us_dollar_mp.symbol_ahead
assert us_dollar_mp.symbol_separator == '_'
assert us_dollar_mp.localized_symbol == 'MP$'
assert us_dollar_mp.convertion == ''
assert us_dollar_mp.__hash__() == hash(
(us_dollar_mp.__class__, decimal, 'USD', '840'))
assert us_dollar_mp.__repr__() == (
'USDollarMP(amount: 1000, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "MP$", '
'numeric_code: "840", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert us_dollar_mp.__str__() == 'USD 10,00.00000'
def test_us_dollar_mp_changed(self):
"""test_cus_dollar_mp_changed."""
us_dollar_mp = USDollarMP(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mp.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mp.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mp.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mp.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mp.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mp.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mp.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mp.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mp.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mp.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mp.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mp.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_mp.international = True
def test_us_dollar_mp_math_add(self):
"""test_us_dollar_mp_math_add."""
us_dollar_mp_one = USDollarMP(amount=1)
us_dollar_mp_two = USDollarMP(amount=2)
us_dollar_mp_three = USDollarMP(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency USD and OTHER.'):
_ = us_dollar_mp_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.USDollarMP\'> '
'and <class \'str\'>.')):
_ = us_dollar_mp_one.__add__('1.00')
assert (
us_dollar_mp_one +
us_dollar_mp_two) == us_dollar_mp_three
def test_us_dollar_mp_slots(self):
"""test_us_dollar_mp_slots."""
us_dollar_mp = USDollarMP(amount=1000)
with raises(
AttributeError,
match=(
'\'USDollarMP\' '
'object has no attribute \'new_variable\'')):
us_dollar_mp.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the US Dollar PC representation."""
from multicurrency import USDollarPC
class TestUSDollarPC:
"""USDollarPC currency tests."""
def test_us_dollar_pc(self):
"""test_us_dollar_pc."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
us_dollar_pc = USDollarPC(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_pc.amount == decimal
assert us_dollar_pc.numeric_code == '840'
assert us_dollar_pc.alpha_code == 'USD'
assert us_dollar_pc.decimal_places == 2
assert us_dollar_pc.decimal_sign == '.'
assert us_dollar_pc.grouping_places == 3
assert us_dollar_pc.grouping_sign == ','
assert not us_dollar_pc.international
assert us_dollar_pc.symbol == '$'
assert us_dollar_pc.symbol_ahead
assert us_dollar_pc.symbol_separator == ''
assert us_dollar_pc.localized_symbol == 'PC$'
assert us_dollar_pc.convertion == ''
assert us_dollar_pc.__hash__() == hash(
(us_dollar_pc.__class__, decimal, 'USD', '840'))
assert us_dollar_pc.__repr__() == (
'USDollarPC(amount: 0.1428571428571428571428571429, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "PC$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_pc.__str__() == '$0.14'
def test_us_dollar_pc_negative(self):
"""test_us_dollar_pc_negative."""
amount = -100
us_dollar_pc = USDollarPC(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_pc.numeric_code == '840'
assert us_dollar_pc.alpha_code == 'USD'
assert us_dollar_pc.decimal_places == 2
assert us_dollar_pc.decimal_sign == '.'
assert us_dollar_pc.grouping_places == 3
assert us_dollar_pc.grouping_sign == ','
assert not us_dollar_pc.international
assert us_dollar_pc.symbol == '$'
assert us_dollar_pc.symbol_ahead
assert us_dollar_pc.symbol_separator == ''
assert us_dollar_pc.localized_symbol == 'PC$'
assert us_dollar_pc.convertion == ''
assert us_dollar_pc.__hash__() == hash(
(us_dollar_pc.__class__, decimal, 'USD', '840'))
assert us_dollar_pc.__repr__() == (
'USDollarPC(amount: -100, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "PC$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_pc.__str__() == '$-100.00'
def test_us_dollar_pc_custom(self):
"""test_us_dollar_pc_custom."""
amount = 1000
us_dollar_pc = USDollarPC(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_pc.amount == decimal
assert us_dollar_pc.numeric_code == '840'
assert us_dollar_pc.alpha_code == 'USD'
assert us_dollar_pc.decimal_places == 5
assert us_dollar_pc.decimal_sign == ','
assert us_dollar_pc.grouping_places == 2
assert us_dollar_pc.grouping_sign == '.'
assert us_dollar_pc.international
assert us_dollar_pc.symbol == '$'
assert not us_dollar_pc.symbol_ahead
assert us_dollar_pc.symbol_separator == '_'
assert us_dollar_pc.localized_symbol == 'PC$'
assert us_dollar_pc.convertion == ''
assert us_dollar_pc.__hash__() == hash(
(us_dollar_pc.__class__, decimal, 'USD', '840'))
assert us_dollar_pc.__repr__() == (
'USDollarPC(amount: 1000, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "PC$", '
'numeric_code: "840", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert us_dollar_pc.__str__() == 'USD 10,00.00000'
def test_us_dollar_pc_changed(self):
"""test_cus_dollar_pc_changed."""
us_dollar_pc = USDollarPC(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pc.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pc.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pc.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pc.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pc.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pc.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pc.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pc.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pc.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pc.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pc.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pc.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pc.international = True
def test_us_dollar_pc_math_add(self):
"""test_us_dollar_pc_math_add."""
us_dollar_pc_one = USDollarPC(amount=1)
us_dollar_pc_two = USDollarPC(amount=2)
us_dollar_pc_three = USDollarPC(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency USD and OTHER.'):
_ = us_dollar_pc_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.USDollarPC\'> '
'and <class \'str\'>.')):
_ = us_dollar_pc_one.__add__('1.00')
assert (
us_dollar_pc_one +
us_dollar_pc_two) == us_dollar_pc_three
def test_us_dollar_pc_slots(self):
"""test_us_dollar_pc_slots."""
us_dollar_pc = USDollarPC(amount=1000)
with raises(
AttributeError,
match=(
'\'USDollarPC\' '
'object has no attribute \'new_variable\'')):
us_dollar_pc.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the US Dollar PW representation."""
from multicurrency import USDollarPW
class TestUSDollarPW:
"""USDollarPW currency tests."""
def test_us_dollar_pw(self):
"""test_us_dollar_pw."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
us_dollar_pw = USDollarPW(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_pw.amount == decimal
assert us_dollar_pw.numeric_code == '840'
assert us_dollar_pw.alpha_code == 'USD'
assert us_dollar_pw.decimal_places == 2
assert us_dollar_pw.decimal_sign == '.'
assert us_dollar_pw.grouping_places == 3
assert us_dollar_pw.grouping_sign == ','
assert not us_dollar_pw.international
assert us_dollar_pw.symbol == '$'
assert us_dollar_pw.symbol_ahead
assert us_dollar_pw.symbol_separator == ''
assert us_dollar_pw.localized_symbol == 'PW$'
assert us_dollar_pw.convertion == ''
assert us_dollar_pw.__hash__() == hash(
(us_dollar_pw.__class__, decimal, 'USD', '840'))
assert us_dollar_pw.__repr__() == (
'USDollarPW(amount: 0.1428571428571428571428571429, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "PW$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_pw.__str__() == '$0.14'
def test_us_dollar_pw_negative(self):
"""test_us_dollar_pw_negative."""
amount = -100
us_dollar_pw = USDollarPW(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_pw.numeric_code == '840'
assert us_dollar_pw.alpha_code == 'USD'
assert us_dollar_pw.decimal_places == 2
assert us_dollar_pw.decimal_sign == '.'
assert us_dollar_pw.grouping_places == 3
assert us_dollar_pw.grouping_sign == ','
assert not us_dollar_pw.international
assert us_dollar_pw.symbol == '$'
assert us_dollar_pw.symbol_ahead
assert us_dollar_pw.symbol_separator == ''
assert us_dollar_pw.localized_symbol == 'PW$'
assert us_dollar_pw.convertion == ''
assert us_dollar_pw.__hash__() == hash(
(us_dollar_pw.__class__, decimal, 'USD', '840'))
assert us_dollar_pw.__repr__() == (
'USDollarPW(amount: -100, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "PW$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_pw.__str__() == '$-100.00'
def test_us_dollar_pw_custom(self):
"""test_us_dollar_pw_custom."""
amount = 1000
us_dollar_pw = USDollarPW(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_pw.amount == decimal
assert us_dollar_pw.numeric_code == '840'
assert us_dollar_pw.alpha_code == 'USD'
assert us_dollar_pw.decimal_places == 5
assert us_dollar_pw.decimal_sign == ','
assert us_dollar_pw.grouping_places == 2
assert us_dollar_pw.grouping_sign == '.'
assert us_dollar_pw.international
assert us_dollar_pw.symbol == '$'
assert not us_dollar_pw.symbol_ahead
assert us_dollar_pw.symbol_separator == '_'
assert us_dollar_pw.localized_symbol == 'PW$'
assert us_dollar_pw.convertion == ''
assert us_dollar_pw.__hash__() == hash(
(us_dollar_pw.__class__, decimal, 'USD', '840'))
assert us_dollar_pw.__repr__() == (
'USDollarPW(amount: 1000, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "PW$", '
'numeric_code: "840", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert us_dollar_pw.__str__() == 'USD 10,00.00000'
def test_us_dollar_pw_changed(self):
"""test_cus_dollar_pw_changed."""
us_dollar_pw = USDollarPW(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pw.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pw.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pw.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pw.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pw.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pw.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pw.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pw.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pw.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pw.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pw.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pw.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pw.international = True
def test_us_dollar_pw_math_add(self):
"""test_us_dollar_pw_math_add."""
us_dollar_pw_one = USDollarPW(amount=1)
us_dollar_pw_two = USDollarPW(amount=2)
us_dollar_pw_three = USDollarPW(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency USD and OTHER.'):
_ = us_dollar_pw_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.USDollarPW\'> '
'and <class \'str\'>.')):
_ = us_dollar_pw_one.__add__('1.00')
assert (
us_dollar_pw_one +
us_dollar_pw_two) == us_dollar_pw_three
def test_us_dollar_pw_slots(self):
"""test_us_dollar_pw_slots."""
us_dollar_pw = USDollarPW(amount=1000)
with raises(
AttributeError,
match=(
'\'USDollarPW\' '
'object has no attribute \'new_variable\'')):
us_dollar_pw.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the US Dollar PA representation."""
from multicurrency import USDollarPA
class TestUSDollarPA:
"""USDollarPA currency tests."""
def test_us_dollar_pa(self):
"""test_us_dollar_pa."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
us_dollar_pa = USDollarPA(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_pa.amount == decimal
assert us_dollar_pa.numeric_code == '840'
assert us_dollar_pa.alpha_code == 'USD'
assert us_dollar_pa.decimal_places == 2
assert us_dollar_pa.decimal_sign == '.'
assert us_dollar_pa.grouping_places == 3
assert us_dollar_pa.grouping_sign == ','
assert not us_dollar_pa.international
assert us_dollar_pa.symbol == '$'
assert us_dollar_pa.symbol_ahead
assert us_dollar_pa.symbol_separator == ''
assert us_dollar_pa.localized_symbol == 'PA$'
assert us_dollar_pa.convertion == ''
assert us_dollar_pa.__hash__() == hash(
(us_dollar_pa.__class__, decimal, 'USD', '840'))
assert us_dollar_pa.__repr__() == (
'USDollarPA(amount: 0.1428571428571428571428571429, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "PA$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_pa.__str__() == '$0.14'
def test_us_dollar_pa_negative(self):
"""test_us_dollar_pa_negative."""
amount = -100
us_dollar_pa = USDollarPA(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_pa.numeric_code == '840'
assert us_dollar_pa.alpha_code == 'USD'
assert us_dollar_pa.decimal_places == 2
assert us_dollar_pa.decimal_sign == '.'
assert us_dollar_pa.grouping_places == 3
assert us_dollar_pa.grouping_sign == ','
assert not us_dollar_pa.international
assert us_dollar_pa.symbol == '$'
assert us_dollar_pa.symbol_ahead
assert us_dollar_pa.symbol_separator == ''
assert us_dollar_pa.localized_symbol == 'PA$'
assert us_dollar_pa.convertion == ''
assert us_dollar_pa.__hash__() == hash(
(us_dollar_pa.__class__, decimal, 'USD', '840'))
assert us_dollar_pa.__repr__() == (
'USDollarPA(amount: -100, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "PA$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_pa.__str__() == '$-100.00'
def test_us_dollar_pa_custom(self):
"""test_us_dollar_pa_custom."""
amount = 1000
us_dollar_pa = USDollarPA(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_pa.amount == decimal
assert us_dollar_pa.numeric_code == '840'
assert us_dollar_pa.alpha_code == 'USD'
assert us_dollar_pa.decimal_places == 5
assert us_dollar_pa.decimal_sign == ','
assert us_dollar_pa.grouping_places == 2
assert us_dollar_pa.grouping_sign == '.'
assert us_dollar_pa.international
assert us_dollar_pa.symbol == '$'
assert not us_dollar_pa.symbol_ahead
assert us_dollar_pa.symbol_separator == '_'
assert us_dollar_pa.localized_symbol == 'PA$'
assert us_dollar_pa.convertion == ''
assert us_dollar_pa.__hash__() == hash(
(us_dollar_pa.__class__, decimal, 'USD', '840'))
assert us_dollar_pa.__repr__() == (
'USDollarPA(amount: 1000, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "PA$", '
'numeric_code: "840", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert us_dollar_pa.__str__() == 'USD 10,00.00000'
def test_us_dollar_pa_changed(self):
"""test_cus_dollar_pa_changed."""
us_dollar_pa = USDollarPA(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pa.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pa.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pa.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pa.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pa.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pa.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pa.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pa.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pa.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pa.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pa.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pa.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pa.international = True
def test_us_dollar_pa_math_add(self):
"""test_us_dollar_pa_math_add."""
us_dollar_pa_one = USDollarPA(amount=1)
us_dollar_pa_two = USDollarPA(amount=2)
us_dollar_pa_three = USDollarPA(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency USD and OTHER.'):
_ = us_dollar_pa_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.USDollarPA\'> '
'and <class \'str\'>.')):
_ = us_dollar_pa_one.__add__('1.00')
assert (
us_dollar_pa_one +
us_dollar_pa_two) == us_dollar_pa_three
def test_us_dollar_pa_slots(self):
"""test_us_dollar_pa_slots."""
us_dollar_pa = USDollarPA(amount=1000)
with raises(
AttributeError,
match=(
'\'USDollarPA\' '
'object has no attribute \'new_variable\'')):
us_dollar_pa.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the US Dollar PR representation."""
from multicurrency import USDollarPR
class TestUSDollarPR:
"""USDollarPR currency tests."""
def test_us_dollar_pr(self):
"""test_us_dollar_pr."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
us_dollar_pr = USDollarPR(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_pr.amount == decimal
assert us_dollar_pr.numeric_code == '840'
assert us_dollar_pr.alpha_code == 'USD'
assert us_dollar_pr.decimal_places == 2
assert us_dollar_pr.decimal_sign == '.'
assert us_dollar_pr.grouping_places == 3
assert us_dollar_pr.grouping_sign == ','
assert not us_dollar_pr.international
assert us_dollar_pr.symbol == '$'
assert us_dollar_pr.symbol_ahead
assert us_dollar_pr.symbol_separator == ''
assert us_dollar_pr.localized_symbol == 'PR$'
assert us_dollar_pr.convertion == ''
assert us_dollar_pr.__hash__() == hash(
(us_dollar_pr.__class__, decimal, 'USD', '840'))
assert us_dollar_pr.__repr__() == (
'USDollarPR(amount: 0.1428571428571428571428571429, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "PR$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_pr.__str__() == '$0.14'
def test_us_dollar_pr_negative(self):
"""test_us_dollar_pr_negative."""
amount = -100
us_dollar_pr = USDollarPR(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_pr.numeric_code == '840'
assert us_dollar_pr.alpha_code == 'USD'
assert us_dollar_pr.decimal_places == 2
assert us_dollar_pr.decimal_sign == '.'
assert us_dollar_pr.grouping_places == 3
assert us_dollar_pr.grouping_sign == ','
assert not us_dollar_pr.international
assert us_dollar_pr.symbol == '$'
assert us_dollar_pr.symbol_ahead
assert us_dollar_pr.symbol_separator == ''
assert us_dollar_pr.localized_symbol == 'PR$'
assert us_dollar_pr.convertion == ''
assert us_dollar_pr.__hash__() == hash(
(us_dollar_pr.__class__, decimal, 'USD', '840'))
assert us_dollar_pr.__repr__() == (
'USDollarPR(amount: -100, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "PR$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_pr.__str__() == '$-100.00'
def test_us_dollar_pr_custom(self):
"""test_us_dollar_pr_custom."""
amount = 1000
us_dollar_pr = USDollarPR(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_pr.amount == decimal
assert us_dollar_pr.numeric_code == '840'
assert us_dollar_pr.alpha_code == 'USD'
assert us_dollar_pr.decimal_places == 5
assert us_dollar_pr.decimal_sign == ','
assert us_dollar_pr.grouping_places == 2
assert us_dollar_pr.grouping_sign == '.'
assert us_dollar_pr.international
assert us_dollar_pr.symbol == '$'
assert not us_dollar_pr.symbol_ahead
assert us_dollar_pr.symbol_separator == '_'
assert us_dollar_pr.localized_symbol == 'PR$'
assert us_dollar_pr.convertion == ''
assert us_dollar_pr.__hash__() == hash(
(us_dollar_pr.__class__, decimal, 'USD', '840'))
assert us_dollar_pr.__repr__() == (
'USDollarPR(amount: 1000, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "PR$", '
'numeric_code: "840", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert us_dollar_pr.__str__() == 'USD 10,00.00000'
def test_us_dollar_pr_changed(self):
"""test_cus_dollar_pr_changed."""
us_dollar_pr = USDollarPR(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pr.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pr.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pr.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pr.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pr.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pr.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pr.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pr.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pr.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pr.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pr.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pr.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_pr.international = True
def test_us_dollar_pr_math_add(self):
"""test_us_dollar_pr_math_add."""
us_dollar_pr_one = USDollarPR(amount=1)
us_dollar_pr_two = USDollarPR(amount=2)
us_dollar_pr_three = USDollarPR(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency USD and OTHER.'):
_ = us_dollar_pr_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.USDollarPR\'> '
'and <class \'str\'>.')):
_ = us_dollar_pr_one.__add__('1.00')
assert (
us_dollar_pr_one +
us_dollar_pr_two) == us_dollar_pr_three
def test_us_dollar_pr_slots(self):
"""test_us_dollar_pr_slots."""
us_dollar_pr = USDollarPR(amount=1000)
with raises(
AttributeError,
match=(
'\'USDollarPR\' '
'object has no attribute \'new_variable\'')):
us_dollar_pr.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the US Dollar TC representation."""
from multicurrency import USDollarTC
class TestUSDollarTC:
"""USDollarTC currency tests."""
def test_us_dollar_tc(self):
"""test_us_dollar_tc."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
us_dollar_tc = USDollarTC(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_tc.amount == decimal
assert us_dollar_tc.numeric_code == '840'
assert us_dollar_tc.alpha_code == 'USD'
assert us_dollar_tc.decimal_places == 2
assert us_dollar_tc.decimal_sign == '.'
assert us_dollar_tc.grouping_places == 3
assert us_dollar_tc.grouping_sign == ','
assert not us_dollar_tc.international
assert us_dollar_tc.symbol == '$'
assert us_dollar_tc.symbol_ahead
assert us_dollar_tc.symbol_separator == ''
assert us_dollar_tc.localized_symbol == 'TC$'
assert us_dollar_tc.convertion == ''
assert us_dollar_tc.__hash__() == hash(
(us_dollar_tc.__class__, decimal, 'USD', '840'))
assert us_dollar_tc.__repr__() == (
'USDollarTC(amount: 0.1428571428571428571428571429, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "TC$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_tc.__str__() == '$0.14'
def test_us_dollar_tc_negative(self):
"""test_us_dollar_tc_negative."""
amount = -100
us_dollar_tc = USDollarTC(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_tc.numeric_code == '840'
assert us_dollar_tc.alpha_code == 'USD'
assert us_dollar_tc.decimal_places == 2
assert us_dollar_tc.decimal_sign == '.'
assert us_dollar_tc.grouping_places == 3
assert us_dollar_tc.grouping_sign == ','
assert not us_dollar_tc.international
assert us_dollar_tc.symbol == '$'
assert us_dollar_tc.symbol_ahead
assert us_dollar_tc.symbol_separator == ''
assert us_dollar_tc.localized_symbol == 'TC$'
assert us_dollar_tc.convertion == ''
assert us_dollar_tc.__hash__() == hash(
(us_dollar_tc.__class__, decimal, 'USD', '840'))
assert us_dollar_tc.__repr__() == (
'USDollarTC(amount: -100, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "TC$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_tc.__str__() == '$-100.00'
def test_us_dollar_tc_custom(self):
"""test_us_dollar_tc_custom."""
amount = 1000
us_dollar_tc = USDollarTC(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_tc.amount == decimal
assert us_dollar_tc.numeric_code == '840'
assert us_dollar_tc.alpha_code == 'USD'
assert us_dollar_tc.decimal_places == 5
assert us_dollar_tc.decimal_sign == ','
assert us_dollar_tc.grouping_places == 2
assert us_dollar_tc.grouping_sign == '.'
assert us_dollar_tc.international
assert us_dollar_tc.symbol == '$'
assert not us_dollar_tc.symbol_ahead
assert us_dollar_tc.symbol_separator == '_'
assert us_dollar_tc.localized_symbol == 'TC$'
assert us_dollar_tc.convertion == ''
assert us_dollar_tc.__hash__() == hash(
(us_dollar_tc.__class__, decimal, 'USD', '840'))
assert us_dollar_tc.__repr__() == (
'USDollarTC(amount: 1000, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "TC$", '
'numeric_code: "840", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert us_dollar_tc.__str__() == 'USD 10,00.00000'
def test_us_dollar_tc_changed(self):
"""test_cus_dollar_tc_changed."""
us_dollar_tc = USDollarTC(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_tc.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_tc.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_tc.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_tc.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_tc.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_tc.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_tc.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_tc.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_tc.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_tc.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_tc.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_tc.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_tc.international = True
def test_us_dollar_tc_math_add(self):
"""test_us_dollar_tc_math_add."""
us_dollar_tc_one = USDollarTC(amount=1)
us_dollar_tc_two = USDollarTC(amount=2)
us_dollar_tc_three = USDollarTC(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency USD and OTHER.'):
_ = us_dollar_tc_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.USDollarTC\'> '
'and <class \'str\'>.')):
_ = us_dollar_tc_one.__add__('1.00')
assert (
us_dollar_tc_one +
us_dollar_tc_two) == us_dollar_tc_three
def test_us_dollar_tc_slots(self):
"""test_us_dollar_tc_slots."""
us_dollar_tc = USDollarTC(amount=1000)
with raises(
AttributeError,
match=(
'\'USDollarTC\' '
'object has no attribute \'new_variable\'')):
us_dollar_tc.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the US Dollar VI representation."""
from multicurrency import USDollarVI
class TestUSDollarVI:
"""USDollarVI currency tests."""
def test_us_dollar_vi(self):
"""test_us_dollar_vi."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
us_dollar_vi = USDollarVI(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_vi.amount == decimal
assert us_dollar_vi.numeric_code == '840'
assert us_dollar_vi.alpha_code == 'USD'
assert us_dollar_vi.decimal_places == 2
assert us_dollar_vi.decimal_sign == '.'
assert us_dollar_vi.grouping_places == 3
assert us_dollar_vi.grouping_sign == ','
assert not us_dollar_vi.international
assert us_dollar_vi.symbol == '$'
assert us_dollar_vi.symbol_ahead
assert us_dollar_vi.symbol_separator == ''
assert us_dollar_vi.localized_symbol == 'VI$'
assert us_dollar_vi.convertion == ''
assert us_dollar_vi.__hash__() == hash(
(us_dollar_vi.__class__, decimal, 'USD', '840'))
assert us_dollar_vi.__repr__() == (
'USDollarVI(amount: 0.1428571428571428571428571429, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "VI$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_vi.__str__() == '$0.14'
def test_us_dollar_vi_negative(self):
"""test_us_dollar_vi_negative."""
amount = -100
us_dollar_vi = USDollarVI(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_vi.numeric_code == '840'
assert us_dollar_vi.alpha_code == 'USD'
assert us_dollar_vi.decimal_places == 2
assert us_dollar_vi.decimal_sign == '.'
assert us_dollar_vi.grouping_places == 3
assert us_dollar_vi.grouping_sign == ','
assert not us_dollar_vi.international
assert us_dollar_vi.symbol == '$'
assert us_dollar_vi.symbol_ahead
assert us_dollar_vi.symbol_separator == ''
assert us_dollar_vi.localized_symbol == 'VI$'
assert us_dollar_vi.convertion == ''
assert us_dollar_vi.__hash__() == hash(
(us_dollar_vi.__class__, decimal, 'USD', '840'))
assert us_dollar_vi.__repr__() == (
'USDollarVI(amount: -100, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "VI$", '
'numeric_code: "840", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert us_dollar_vi.__str__() == '$-100.00'
def test_us_dollar_vi_custom(self):
"""test_us_dollar_vi_custom."""
amount = 1000
us_dollar_vi = USDollarVI(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert us_dollar_vi.amount == decimal
assert us_dollar_vi.numeric_code == '840'
assert us_dollar_vi.alpha_code == 'USD'
assert us_dollar_vi.decimal_places == 5
assert us_dollar_vi.decimal_sign == ','
assert us_dollar_vi.grouping_places == 2
assert us_dollar_vi.grouping_sign == '.'
assert us_dollar_vi.international
assert us_dollar_vi.symbol == '$'
assert not us_dollar_vi.symbol_ahead
assert us_dollar_vi.symbol_separator == '_'
assert us_dollar_vi.localized_symbol == 'VI$'
assert us_dollar_vi.convertion == ''
assert us_dollar_vi.__hash__() == hash(
(us_dollar_vi.__class__, decimal, 'USD', '840'))
assert us_dollar_vi.__repr__() == (
'USDollarVI(amount: 1000, '
'alpha_code: "USD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "VI$", '
'numeric_code: "840", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert us_dollar_vi.__str__() == 'USD 10,00.00000'
def test_us_dollar_vi_changed(self):
"""test_cus_dollar_vi_changed."""
us_dollar_vi = USDollarVI(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vi.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vi.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vi.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vi.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vi.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vi.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vi.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vi.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vi.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vi.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vi.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vi.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
us_dollar_vi.international = True
def test_us_dollar_vi_math_add(self):
"""test_us_dollar_vi_math_add."""
us_dollar_vi_one = USDollarVI(amount=1)
us_dollar_vi_two = USDollarVI(amount=2)
us_dollar_vi_three = USDollarVI(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency USD and OTHER.'):
_ = us_dollar_vi_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.USDollarVI\'> '
'and <class \'str\'>.')):
_ = us_dollar_vi_one.__add__('1.00')
assert (
us_dollar_vi_one +
us_dollar_vi_two) == us_dollar_vi_three
def test_us_dollar_vi_slots(self):
"""test_us_dollar_vi_slots."""
us_dollar_vi = USDollarVI(amount=1000)
with raises(
AttributeError,
match=(
'\'USDollarVI\' '
'object has no attribute \'new_variable\'')):
us_dollar_vi.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Eastern Caribbean Dollar representation."""
from multicurrency import EasternCaribbeanDollar
class TestEasternCaribbeanDollar:
"""EasternCaribbeanDollar currency tests."""
def test_eastern_caribbean_dollar(self):
"""test_eastern_caribbean_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
eastern_caribbean_dollar = EasternCaribbeanDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar.amount == decimal
assert eastern_caribbean_dollar.numeric_code == '951'
assert eastern_caribbean_dollar.alpha_code == 'XCD'
assert eastern_caribbean_dollar.decimal_places == 2
assert eastern_caribbean_dollar.decimal_sign == '.'
assert eastern_caribbean_dollar.grouping_places == 3
assert eastern_caribbean_dollar.grouping_sign == ','
assert not eastern_caribbean_dollar.international
assert eastern_caribbean_dollar.symbol == '$'
assert eastern_caribbean_dollar.symbol_ahead
assert eastern_caribbean_dollar.symbol_separator == ''
assert eastern_caribbean_dollar.localized_symbol == '$'
assert eastern_caribbean_dollar.convertion == ''
assert eastern_caribbean_dollar.__hash__() == hash(
(eastern_caribbean_dollar.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar.__repr__() == (
'EasternCaribbeanDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar.__str__() == '$0.14'
def test_eastern_caribbean_dollar_negative(self):
"""test_eastern_caribbean_dollar_negative."""
amount = -100
eastern_caribbean_dollar = EasternCaribbeanDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar.numeric_code == '951'
assert eastern_caribbean_dollar.alpha_code == 'XCD'
assert eastern_caribbean_dollar.decimal_places == 2
assert eastern_caribbean_dollar.decimal_sign == '.'
assert eastern_caribbean_dollar.grouping_places == 3
assert eastern_caribbean_dollar.grouping_sign == ','
assert not eastern_caribbean_dollar.international
assert eastern_caribbean_dollar.symbol == '$'
assert eastern_caribbean_dollar.symbol_ahead
assert eastern_caribbean_dollar.symbol_separator == ''
assert eastern_caribbean_dollar.localized_symbol == '$'
assert eastern_caribbean_dollar.convertion == ''
assert eastern_caribbean_dollar.__hash__() == hash(
(eastern_caribbean_dollar.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar.__repr__() == (
'EasternCaribbeanDollar(amount: -100, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar.__str__() == '$-100.00'
def test_eastern_caribbean_dollar_custom(self):
"""test_eastern_caribbean_dollar_custom."""
amount = 1000
eastern_caribbean_dollar = EasternCaribbeanDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar.amount == decimal
assert eastern_caribbean_dollar.numeric_code == '951'
assert eastern_caribbean_dollar.alpha_code == 'XCD'
assert eastern_caribbean_dollar.decimal_places == 5
assert eastern_caribbean_dollar.decimal_sign == ','
assert eastern_caribbean_dollar.grouping_places == 2
assert eastern_caribbean_dollar.grouping_sign == '.'
assert eastern_caribbean_dollar.international
assert eastern_caribbean_dollar.symbol == '$'
assert not eastern_caribbean_dollar.symbol_ahead
assert eastern_caribbean_dollar.symbol_separator == '_'
assert eastern_caribbean_dollar.localized_symbol == '$'
assert eastern_caribbean_dollar.convertion == ''
assert eastern_caribbean_dollar.__hash__() == hash(
(eastern_caribbean_dollar.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar.__repr__() == (
'EasternCaribbeanDollar(amount: 1000, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "$", '
'numeric_code: "951", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert eastern_caribbean_dollar.__str__() == 'XCD 10,00.00000'
def test_eastern_caribbean_dollar_changed(self):
"""test_ceastern_caribbean_dollar_changed."""
eastern_caribbean_dollar = EasternCaribbeanDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar.international = True
def test_eastern_caribbean_dollar_math_add(self):
"""test_eastern_caribbean_dollar_math_add."""
eastern_caribbean_dollar_one = EasternCaribbeanDollar(amount=1)
eastern_caribbean_dollar_two = EasternCaribbeanDollar(amount=2)
eastern_caribbean_dollar_three = EasternCaribbeanDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency XCD and OTHER.'):
_ = eastern_caribbean_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.EasternCaribbeanDollar\'> '
'and <class \'str\'>.')):
_ = eastern_caribbean_dollar_one.__add__('1.00')
assert (
eastern_caribbean_dollar_one +
eastern_caribbean_dollar_two) == eastern_caribbean_dollar_three
def test_eastern_caribbean_dollar_slots(self):
"""test_eastern_caribbean_dollar_slots."""
eastern_caribbean_dollar = EasternCaribbeanDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'EasternCaribbeanDollar\' '
'object has no attribute \'new_variable\'')):
eastern_caribbean_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Eastern Caribbean Dollar AI representation."""
from multicurrency import EasternCaribbeanDollarAI
class TestEasternCaribbeanDollarAI:
"""EasternCaribbeanDollarAI currency tests."""
def test_eastern_caribbean_dollar_ai(self):
"""test_eastern_caribbean_dollar_ai."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
eastern_caribbean_dollar_ai = EasternCaribbeanDollarAI(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_ai.amount == decimal
assert eastern_caribbean_dollar_ai.numeric_code == '951'
assert eastern_caribbean_dollar_ai.alpha_code == 'XCD'
assert eastern_caribbean_dollar_ai.decimal_places == 2
assert eastern_caribbean_dollar_ai.decimal_sign == '.'
assert eastern_caribbean_dollar_ai.grouping_places == 3
assert eastern_caribbean_dollar_ai.grouping_sign == ','
assert not eastern_caribbean_dollar_ai.international
assert eastern_caribbean_dollar_ai.symbol == '$'
assert eastern_caribbean_dollar_ai.symbol_ahead
assert eastern_caribbean_dollar_ai.symbol_separator == ''
assert eastern_caribbean_dollar_ai.localized_symbol == 'AI$'
assert eastern_caribbean_dollar_ai.convertion == ''
assert eastern_caribbean_dollar_ai.__hash__() == hash(
(eastern_caribbean_dollar_ai.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_ai.__repr__() == (
'EasternCaribbeanDollarAI(amount: 0.1428571428571428571428571429, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "AI$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar_ai.__str__() == '$0.14'
def test_eastern_caribbean_dollar_ai_negative(self):
"""test_eastern_caribbean_dollar_ai_negative."""
amount = -100
eastern_caribbean_dollar_ai = EasternCaribbeanDollarAI(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_ai.numeric_code == '951'
assert eastern_caribbean_dollar_ai.alpha_code == 'XCD'
assert eastern_caribbean_dollar_ai.decimal_places == 2
assert eastern_caribbean_dollar_ai.decimal_sign == '.'
assert eastern_caribbean_dollar_ai.grouping_places == 3
assert eastern_caribbean_dollar_ai.grouping_sign == ','
assert not eastern_caribbean_dollar_ai.international
assert eastern_caribbean_dollar_ai.symbol == '$'
assert eastern_caribbean_dollar_ai.symbol_ahead
assert eastern_caribbean_dollar_ai.symbol_separator == ''
assert eastern_caribbean_dollar_ai.localized_symbol == 'AI$'
assert eastern_caribbean_dollar_ai.convertion == ''
assert eastern_caribbean_dollar_ai.__hash__() == hash(
(eastern_caribbean_dollar_ai.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_ai.__repr__() == (
'EasternCaribbeanDollarAI(amount: -100, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "AI$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar_ai.__str__() == '$-100.00'
def test_eastern_caribbean_dollar_ai_custom(self):
"""test_eastern_caribbean_dollar_ai_custom."""
amount = 1000
eastern_caribbean_dollar_ai = EasternCaribbeanDollarAI(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_ai.amount == decimal
assert eastern_caribbean_dollar_ai.numeric_code == '951'
assert eastern_caribbean_dollar_ai.alpha_code == 'XCD'
assert eastern_caribbean_dollar_ai.decimal_places == 5
assert eastern_caribbean_dollar_ai.decimal_sign == ','
assert eastern_caribbean_dollar_ai.grouping_places == 2
assert eastern_caribbean_dollar_ai.grouping_sign == '.'
assert eastern_caribbean_dollar_ai.international
assert eastern_caribbean_dollar_ai.symbol == '$'
assert not eastern_caribbean_dollar_ai.symbol_ahead
assert eastern_caribbean_dollar_ai.symbol_separator == '_'
assert eastern_caribbean_dollar_ai.localized_symbol == 'AI$'
assert eastern_caribbean_dollar_ai.convertion == ''
assert eastern_caribbean_dollar_ai.__hash__() == hash(
(eastern_caribbean_dollar_ai.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_ai.__repr__() == (
'EasternCaribbeanDollarAI(amount: 1000, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "AI$", '
'numeric_code: "951", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert eastern_caribbean_dollar_ai.__str__() == 'XCD 10,00.00000'
def test_eastern_caribbean_dollar_ai_changed(self):
"""test_ceastern_caribbean_dollar_ai_changed."""
eastern_caribbean_dollar_ai = EasternCaribbeanDollarAI(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ai.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ai.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ai.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ai.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ai.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ai.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ai.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ai.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ai.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ai.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ai.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ai.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ai.international = True
def test_eastern_caribbean_dollar_ai_math_add(self):
"""test_eastern_caribbean_dollar_ai_math_add."""
eastern_caribbean_dollar_ai_one = EasternCaribbeanDollarAI(amount=1)
eastern_caribbean_dollar_ai_two = EasternCaribbeanDollarAI(amount=2)
eastern_caribbean_dollar_ai_three = EasternCaribbeanDollarAI(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency XCD and OTHER.'):
_ = eastern_caribbean_dollar_ai_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.EasternCaribbeanDollarAI\'> '
'and <class \'str\'>.')):
_ = eastern_caribbean_dollar_ai_one.__add__('1.00')
assert (
eastern_caribbean_dollar_ai_one +
eastern_caribbean_dollar_ai_two) == eastern_caribbean_dollar_ai_three
def test_eastern_caribbean_dollar_ai_slots(self):
"""test_eastern_caribbean_dollar_ai_slots."""
eastern_caribbean_dollar_ai = EasternCaribbeanDollarAI(amount=1000)
with raises(
AttributeError,
match=(
'\'EasternCaribbeanDollarAI\' '
'object has no attribute \'new_variable\'')):
eastern_caribbean_dollar_ai.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Eastern Caribbean Dollar AG representation."""
from multicurrency import EasternCaribbeanDollarAG
class TestEasternCaribbeanDollarAG:
"""EasternCaribbeanDollarAG currency tests."""
def test_eastern_caribbean_dollar_ag(self):
"""test_eastern_caribbean_dollar_ag."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
eastern_caribbean_dollar_ag = EasternCaribbeanDollarAG(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_ag.amount == decimal
assert eastern_caribbean_dollar_ag.numeric_code == '951'
assert eastern_caribbean_dollar_ag.alpha_code == 'XCD'
assert eastern_caribbean_dollar_ag.decimal_places == 2
assert eastern_caribbean_dollar_ag.decimal_sign == '.'
assert eastern_caribbean_dollar_ag.grouping_places == 3
assert eastern_caribbean_dollar_ag.grouping_sign == ','
assert not eastern_caribbean_dollar_ag.international
assert eastern_caribbean_dollar_ag.symbol == '$'
assert eastern_caribbean_dollar_ag.symbol_ahead
assert eastern_caribbean_dollar_ag.symbol_separator == ''
assert eastern_caribbean_dollar_ag.localized_symbol == 'AG$'
assert eastern_caribbean_dollar_ag.convertion == ''
assert eastern_caribbean_dollar_ag.__hash__() == hash(
(eastern_caribbean_dollar_ag.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_ag.__repr__() == (
'EasternCaribbeanDollarAG(amount: 0.1428571428571428571428571429, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "AG$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar_ag.__str__() == '$0.14'
def test_eastern_caribbean_dollar_ag_negative(self):
"""test_eastern_caribbean_dollar_ag_negative."""
amount = -100
eastern_caribbean_dollar_ag = EasternCaribbeanDollarAG(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_ag.numeric_code == '951'
assert eastern_caribbean_dollar_ag.alpha_code == 'XCD'
assert eastern_caribbean_dollar_ag.decimal_places == 2
assert eastern_caribbean_dollar_ag.decimal_sign == '.'
assert eastern_caribbean_dollar_ag.grouping_places == 3
assert eastern_caribbean_dollar_ag.grouping_sign == ','
assert not eastern_caribbean_dollar_ag.international
assert eastern_caribbean_dollar_ag.symbol == '$'
assert eastern_caribbean_dollar_ag.symbol_ahead
assert eastern_caribbean_dollar_ag.symbol_separator == ''
assert eastern_caribbean_dollar_ag.localized_symbol == 'AG$'
assert eastern_caribbean_dollar_ag.convertion == ''
assert eastern_caribbean_dollar_ag.__hash__() == hash(
(eastern_caribbean_dollar_ag.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_ag.__repr__() == (
'EasternCaribbeanDollarAG(amount: -100, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "AG$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar_ag.__str__() == '$-100.00'
def test_eastern_caribbean_dollar_ag_custom(self):
"""test_eastern_caribbean_dollar_ag_custom."""
amount = 1000
eastern_caribbean_dollar_ag = EasternCaribbeanDollarAG(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_ag.amount == decimal
assert eastern_caribbean_dollar_ag.numeric_code == '951'
assert eastern_caribbean_dollar_ag.alpha_code == 'XCD'
assert eastern_caribbean_dollar_ag.decimal_places == 5
assert eastern_caribbean_dollar_ag.decimal_sign == ','
assert eastern_caribbean_dollar_ag.grouping_places == 2
assert eastern_caribbean_dollar_ag.grouping_sign == '.'
assert eastern_caribbean_dollar_ag.international
assert eastern_caribbean_dollar_ag.symbol == '$'
assert not eastern_caribbean_dollar_ag.symbol_ahead
assert eastern_caribbean_dollar_ag.symbol_separator == '_'
assert eastern_caribbean_dollar_ag.localized_symbol == 'AG$'
assert eastern_caribbean_dollar_ag.convertion == ''
assert eastern_caribbean_dollar_ag.__hash__() == hash(
(eastern_caribbean_dollar_ag.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_ag.__repr__() == (
'EasternCaribbeanDollarAG(amount: 1000, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "AG$", '
'numeric_code: "951", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert eastern_caribbean_dollar_ag.__str__() == 'XCD 10,00.00000'
def test_eastern_caribbean_dollar_ag_changed(self):
"""test_ceastern_caribbean_dollar_ag_changed."""
eastern_caribbean_dollar_ag = EasternCaribbeanDollarAG(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ag.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ag.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ag.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ag.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ag.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ag.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ag.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ag.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ag.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ag.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ag.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ag.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ag.international = True
def test_eastern_caribbean_dollar_ag_math_add(self):
"""test_eastern_caribbean_dollar_ag_math_add."""
eastern_caribbean_dollar_ag_one = EasternCaribbeanDollarAG(amount=1)
eastern_caribbean_dollar_ag_two = EasternCaribbeanDollarAG(amount=2)
eastern_caribbean_dollar_ag_three = EasternCaribbeanDollarAG(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency XCD and OTHER.'):
_ = eastern_caribbean_dollar_ag_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.EasternCaribbeanDollarAG\'> '
'and <class \'str\'>.')):
_ = eastern_caribbean_dollar_ag_one.__add__('1.00')
assert (
eastern_caribbean_dollar_ag_one +
eastern_caribbean_dollar_ag_two) == eastern_caribbean_dollar_ag_three
def test_eastern_caribbean_dollar_ag_slots(self):
"""test_eastern_caribbean_dollar_ag_slots."""
eastern_caribbean_dollar_ag = EasternCaribbeanDollarAG(amount=1000)
with raises(
AttributeError,
match=(
'\'EasternCaribbeanDollarAG\' '
'object has no attribute \'new_variable\'')):
eastern_caribbean_dollar_ag.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Eastern Caribbean Dollar DM representation."""
from multicurrency import EasternCaribbeanDollarDM
class TestEasternCaribbeanDollarDM:
"""EasternCaribbeanDollarDM currency tests."""
def test_eastern_caribbean_dollar_dm(self):
"""test_eastern_caribbean_dollar_dm."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
eastern_caribbean_dollar_dm = EasternCaribbeanDollarDM(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_dm.amount == decimal
assert eastern_caribbean_dollar_dm.numeric_code == '951'
assert eastern_caribbean_dollar_dm.alpha_code == 'XCD'
assert eastern_caribbean_dollar_dm.decimal_places == 2
assert eastern_caribbean_dollar_dm.decimal_sign == '.'
assert eastern_caribbean_dollar_dm.grouping_places == 3
assert eastern_caribbean_dollar_dm.grouping_sign == ','
assert not eastern_caribbean_dollar_dm.international
assert eastern_caribbean_dollar_dm.symbol == '$'
assert eastern_caribbean_dollar_dm.symbol_ahead
assert eastern_caribbean_dollar_dm.symbol_separator == ''
assert eastern_caribbean_dollar_dm.localized_symbol == 'DM$'
assert eastern_caribbean_dollar_dm.convertion == ''
assert eastern_caribbean_dollar_dm.__hash__() == hash(
(eastern_caribbean_dollar_dm.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_dm.__repr__() == (
'EasternCaribbeanDollarDM(amount: 0.1428571428571428571428571429, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "DM$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar_dm.__str__() == '$0.14'
def test_eastern_caribbean_dollar_dm_negative(self):
"""test_eastern_caribbean_dollar_dm_negative."""
amount = -100
eastern_caribbean_dollar_dm = EasternCaribbeanDollarDM(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_dm.numeric_code == '951'
assert eastern_caribbean_dollar_dm.alpha_code == 'XCD'
assert eastern_caribbean_dollar_dm.decimal_places == 2
assert eastern_caribbean_dollar_dm.decimal_sign == '.'
assert eastern_caribbean_dollar_dm.grouping_places == 3
assert eastern_caribbean_dollar_dm.grouping_sign == ','
assert not eastern_caribbean_dollar_dm.international
assert eastern_caribbean_dollar_dm.symbol == '$'
assert eastern_caribbean_dollar_dm.symbol_ahead
assert eastern_caribbean_dollar_dm.symbol_separator == ''
assert eastern_caribbean_dollar_dm.localized_symbol == 'DM$'
assert eastern_caribbean_dollar_dm.convertion == ''
assert eastern_caribbean_dollar_dm.__hash__() == hash(
(eastern_caribbean_dollar_dm.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_dm.__repr__() == (
'EasternCaribbeanDollarDM(amount: -100, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "DM$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar_dm.__str__() == '$-100.00'
def test_eastern_caribbean_dollar_dm_custom(self):
"""test_eastern_caribbean_dollar_dm_custom."""
amount = 1000
eastern_caribbean_dollar_dm = EasternCaribbeanDollarDM(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_dm.amount == decimal
assert eastern_caribbean_dollar_dm.numeric_code == '951'
assert eastern_caribbean_dollar_dm.alpha_code == 'XCD'
assert eastern_caribbean_dollar_dm.decimal_places == 5
assert eastern_caribbean_dollar_dm.decimal_sign == ','
assert eastern_caribbean_dollar_dm.grouping_places == 2
assert eastern_caribbean_dollar_dm.grouping_sign == '.'
assert eastern_caribbean_dollar_dm.international
assert eastern_caribbean_dollar_dm.symbol == '$'
assert not eastern_caribbean_dollar_dm.symbol_ahead
assert eastern_caribbean_dollar_dm.symbol_separator == '_'
assert eastern_caribbean_dollar_dm.localized_symbol == 'DM$'
assert eastern_caribbean_dollar_dm.convertion == ''
assert eastern_caribbean_dollar_dm.__hash__() == hash(
(eastern_caribbean_dollar_dm.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_dm.__repr__() == (
'EasternCaribbeanDollarDM(amount: 1000, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "DM$", '
'numeric_code: "951", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert eastern_caribbean_dollar_dm.__str__() == 'XCD 10,00.00000'
def test_eastern_caribbean_dollar_dm_changed(self):
"""test_ceastern_caribbean_dollar_dm_changed."""
eastern_caribbean_dollar_dm = EasternCaribbeanDollarDM(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_dm.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_dm.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_dm.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_dm.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_dm.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_dm.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_dm.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_dm.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_dm.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_dm.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_dm.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_dm.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_dm.international = True
def test_eastern_caribbean_dollar_dm_math_add(self):
"""test_eastern_caribbean_dollar_dm_math_add."""
eastern_caribbean_dollar_dm_one = EasternCaribbeanDollarDM(amount=1)
eastern_caribbean_dollar_dm_two = EasternCaribbeanDollarDM(amount=2)
eastern_caribbean_dollar_dm_three = EasternCaribbeanDollarDM(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency XCD and OTHER.'):
_ = eastern_caribbean_dollar_dm_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.EasternCaribbeanDollarDM\'> '
'and <class \'str\'>.')):
_ = eastern_caribbean_dollar_dm_one.__add__('1.00')
assert (
eastern_caribbean_dollar_dm_one +
eastern_caribbean_dollar_dm_two) == eastern_caribbean_dollar_dm_three
def test_eastern_caribbean_dollar_dm_slots(self):
"""test_eastern_caribbean_dollar_dm_slots."""
eastern_caribbean_dollar_dm = EasternCaribbeanDollarDM(amount=1000)
with raises(
AttributeError,
match=(
'\'EasternCaribbeanDollarDM\' '
'object has no attribute \'new_variable\'')):
eastern_caribbean_dollar_dm.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Eastern Caribbean Dollar GD representation."""
from multicurrency import EasternCaribbeanDollarGD
class TestEasternCaribbeanDollarGD:
"""EasternCaribbeanDollarGD currency tests."""
def test_eastern_caribbean_dollar_gd(self):
"""test_eastern_caribbean_dollar_gd."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
eastern_caribbean_dollar_gd = EasternCaribbeanDollarGD(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_gd.amount == decimal
assert eastern_caribbean_dollar_gd.numeric_code == '951'
assert eastern_caribbean_dollar_gd.alpha_code == 'XCD'
assert eastern_caribbean_dollar_gd.decimal_places == 2
assert eastern_caribbean_dollar_gd.decimal_sign == '.'
assert eastern_caribbean_dollar_gd.grouping_places == 3
assert eastern_caribbean_dollar_gd.grouping_sign == ','
assert not eastern_caribbean_dollar_gd.international
assert eastern_caribbean_dollar_gd.symbol == '$'
assert eastern_caribbean_dollar_gd.symbol_ahead
assert eastern_caribbean_dollar_gd.symbol_separator == ''
assert eastern_caribbean_dollar_gd.localized_symbol == 'GD$'
assert eastern_caribbean_dollar_gd.convertion == ''
assert eastern_caribbean_dollar_gd.__hash__() == hash(
(eastern_caribbean_dollar_gd.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_gd.__repr__() == (
'EasternCaribbeanDollarGD(amount: 0.1428571428571428571428571429, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "GD$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar_gd.__str__() == '$0.14'
def test_eastern_caribbean_dollar_gd_negative(self):
"""test_eastern_caribbean_dollar_gd_negative."""
amount = -100
eastern_caribbean_dollar_gd = EasternCaribbeanDollarGD(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_gd.numeric_code == '951'
assert eastern_caribbean_dollar_gd.alpha_code == 'XCD'
assert eastern_caribbean_dollar_gd.decimal_places == 2
assert eastern_caribbean_dollar_gd.decimal_sign == '.'
assert eastern_caribbean_dollar_gd.grouping_places == 3
assert eastern_caribbean_dollar_gd.grouping_sign == ','
assert not eastern_caribbean_dollar_gd.international
assert eastern_caribbean_dollar_gd.symbol == '$'
assert eastern_caribbean_dollar_gd.symbol_ahead
assert eastern_caribbean_dollar_gd.symbol_separator == ''
assert eastern_caribbean_dollar_gd.localized_symbol == 'GD$'
assert eastern_caribbean_dollar_gd.convertion == ''
assert eastern_caribbean_dollar_gd.__hash__() == hash(
(eastern_caribbean_dollar_gd.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_gd.__repr__() == (
'EasternCaribbeanDollarGD(amount: -100, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "GD$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar_gd.__str__() == '$-100.00'
def test_eastern_caribbean_dollar_gd_custom(self):
"""test_eastern_caribbean_dollar_gd_custom."""
amount = 1000
eastern_caribbean_dollar_gd = EasternCaribbeanDollarGD(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_gd.amount == decimal
assert eastern_caribbean_dollar_gd.numeric_code == '951'
assert eastern_caribbean_dollar_gd.alpha_code == 'XCD'
assert eastern_caribbean_dollar_gd.decimal_places == 5
assert eastern_caribbean_dollar_gd.decimal_sign == ','
assert eastern_caribbean_dollar_gd.grouping_places == 2
assert eastern_caribbean_dollar_gd.grouping_sign == '.'
assert eastern_caribbean_dollar_gd.international
assert eastern_caribbean_dollar_gd.symbol == '$'
assert not eastern_caribbean_dollar_gd.symbol_ahead
assert eastern_caribbean_dollar_gd.symbol_separator == '_'
assert eastern_caribbean_dollar_gd.localized_symbol == 'GD$'
assert eastern_caribbean_dollar_gd.convertion == ''
assert eastern_caribbean_dollar_gd.__hash__() == hash(
(eastern_caribbean_dollar_gd.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_gd.__repr__() == (
'EasternCaribbeanDollarGD(amount: 1000, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "GD$", '
'numeric_code: "951", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert eastern_caribbean_dollar_gd.__str__() == 'XCD 10,00.00000'
def test_eastern_caribbean_dollar_gd_changed(self):
"""test_ceastern_caribbean_dollar_gd_changed."""
eastern_caribbean_dollar_gd = EasternCaribbeanDollarGD(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_gd.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_gd.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_gd.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_gd.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_gd.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_gd.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_gd.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_gd.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_gd.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_gd.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_gd.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_gd.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_gd.international = True
def test_eastern_caribbean_dollar_gd_math_add(self):
"""test_eastern_caribbean_dollar_gd_math_add."""
eastern_caribbean_dollar_gd_one = EasternCaribbeanDollarGD(amount=1)
eastern_caribbean_dollar_gd_two = EasternCaribbeanDollarGD(amount=2)
eastern_caribbean_dollar_gd_three = EasternCaribbeanDollarGD(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency XCD and OTHER.'):
_ = eastern_caribbean_dollar_gd_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.EasternCaribbeanDollarGD\'> '
'and <class \'str\'>.')):
_ = eastern_caribbean_dollar_gd_one.__add__('1.00')
assert (
eastern_caribbean_dollar_gd_one +
eastern_caribbean_dollar_gd_two) == eastern_caribbean_dollar_gd_three
def test_eastern_caribbean_dollar_gd_slots(self):
"""test_eastern_caribbean_dollar_gd_slots."""
eastern_caribbean_dollar_gd = EasternCaribbeanDollarGD(amount=1000)
with raises(
AttributeError,
match=(
'\'EasternCaribbeanDollarGD\' '
'object has no attribute \'new_variable\'')):
eastern_caribbean_dollar_gd.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Eastern Caribbean Dollar MS representation."""
from multicurrency import EasternCaribbeanDollarMS
class TestEasternCaribbeanDollarMS:
"""EasternCaribbeanDollarMS currency tests."""
def test_eastern_caribbean_dollar_ms(self):
"""test_eastern_caribbean_dollar_ms."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
eastern_caribbean_dollar_ms = EasternCaribbeanDollarMS(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_ms.amount == decimal
assert eastern_caribbean_dollar_ms.numeric_code == '951'
assert eastern_caribbean_dollar_ms.alpha_code == 'XCD'
assert eastern_caribbean_dollar_ms.decimal_places == 2
assert eastern_caribbean_dollar_ms.decimal_sign == '.'
assert eastern_caribbean_dollar_ms.grouping_places == 3
assert eastern_caribbean_dollar_ms.grouping_sign == ','
assert not eastern_caribbean_dollar_ms.international
assert eastern_caribbean_dollar_ms.symbol == '$'
assert eastern_caribbean_dollar_ms.symbol_ahead
assert eastern_caribbean_dollar_ms.symbol_separator == ''
assert eastern_caribbean_dollar_ms.localized_symbol == 'MS$'
assert eastern_caribbean_dollar_ms.convertion == ''
assert eastern_caribbean_dollar_ms.__hash__() == hash(
(eastern_caribbean_dollar_ms.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_ms.__repr__() == (
'EasternCaribbeanDollarMS(amount: 0.1428571428571428571428571429, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "MS$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar_ms.__str__() == '$0.14'
def test_eastern_caribbean_dollar_ms_negative(self):
"""test_eastern_caribbean_dollar_ms_negative."""
amount = -100
eastern_caribbean_dollar_ms = EasternCaribbeanDollarMS(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_ms.numeric_code == '951'
assert eastern_caribbean_dollar_ms.alpha_code == 'XCD'
assert eastern_caribbean_dollar_ms.decimal_places == 2
assert eastern_caribbean_dollar_ms.decimal_sign == '.'
assert eastern_caribbean_dollar_ms.grouping_places == 3
assert eastern_caribbean_dollar_ms.grouping_sign == ','
assert not eastern_caribbean_dollar_ms.international
assert eastern_caribbean_dollar_ms.symbol == '$'
assert eastern_caribbean_dollar_ms.symbol_ahead
assert eastern_caribbean_dollar_ms.symbol_separator == ''
assert eastern_caribbean_dollar_ms.localized_symbol == 'MS$'
assert eastern_caribbean_dollar_ms.convertion == ''
assert eastern_caribbean_dollar_ms.__hash__() == hash(
(eastern_caribbean_dollar_ms.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_ms.__repr__() == (
'EasternCaribbeanDollarMS(amount: -100, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "MS$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar_ms.__str__() == '$-100.00'
def test_eastern_caribbean_dollar_ms_custom(self):
"""test_eastern_caribbean_dollar_ms_custom."""
amount = 1000
eastern_caribbean_dollar_ms = EasternCaribbeanDollarMS(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_ms.amount == decimal
assert eastern_caribbean_dollar_ms.numeric_code == '951'
assert eastern_caribbean_dollar_ms.alpha_code == 'XCD'
assert eastern_caribbean_dollar_ms.decimal_places == 5
assert eastern_caribbean_dollar_ms.decimal_sign == ','
assert eastern_caribbean_dollar_ms.grouping_places == 2
assert eastern_caribbean_dollar_ms.grouping_sign == '.'
assert eastern_caribbean_dollar_ms.international
assert eastern_caribbean_dollar_ms.symbol == '$'
assert not eastern_caribbean_dollar_ms.symbol_ahead
assert eastern_caribbean_dollar_ms.symbol_separator == '_'
assert eastern_caribbean_dollar_ms.localized_symbol == 'MS$'
assert eastern_caribbean_dollar_ms.convertion == ''
assert eastern_caribbean_dollar_ms.__hash__() == hash(
(eastern_caribbean_dollar_ms.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_ms.__repr__() == (
'EasternCaribbeanDollarMS(amount: 1000, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "MS$", '
'numeric_code: "951", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert eastern_caribbean_dollar_ms.__str__() == 'XCD 10,00.00000'
def test_eastern_caribbean_dollar_ms_changed(self):
"""test_ceastern_caribbean_dollar_ms_changed."""
eastern_caribbean_dollar_ms = EasternCaribbeanDollarMS(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ms.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ms.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ms.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ms.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ms.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ms.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ms.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ms.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ms.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ms.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ms.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ms.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_ms.international = True
def test_eastern_caribbean_dollar_ms_math_add(self):
"""test_eastern_caribbean_dollar_ms_math_add."""
eastern_caribbean_dollar_ms_one = EasternCaribbeanDollarMS(amount=1)
eastern_caribbean_dollar_ms_two = EasternCaribbeanDollarMS(amount=2)
eastern_caribbean_dollar_ms_three = EasternCaribbeanDollarMS(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency XCD and OTHER.'):
_ = eastern_caribbean_dollar_ms_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.EasternCaribbeanDollarMS\'> '
'and <class \'str\'>.')):
_ = eastern_caribbean_dollar_ms_one.__add__('1.00')
assert (
eastern_caribbean_dollar_ms_one +
eastern_caribbean_dollar_ms_two) == eastern_caribbean_dollar_ms_three
def test_eastern_caribbean_dollar_ms_slots(self):
"""test_eastern_caribbean_dollar_ms_slots."""
eastern_caribbean_dollar_ms = EasternCaribbeanDollarMS(amount=1000)
with raises(
AttributeError,
match=(
'\'EasternCaribbeanDollarMS\' '
'object has no attribute \'new_variable\'')):
eastern_caribbean_dollar_ms.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Eastern Caribbean Dollar KN representation."""
from multicurrency import EasternCaribbeanDollarKN
class TestEasternCaribbeanDollarKN:
"""EasternCaribbeanDollarKN currency tests."""
def test_eastern_caribbean_dollar_kn(self):
"""test_eastern_caribbean_dollar_kn."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
eastern_caribbean_dollar_kn = EasternCaribbeanDollarKN(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_kn.amount == decimal
assert eastern_caribbean_dollar_kn.numeric_code == '951'
assert eastern_caribbean_dollar_kn.alpha_code == 'XCD'
assert eastern_caribbean_dollar_kn.decimal_places == 2
assert eastern_caribbean_dollar_kn.decimal_sign == '.'
assert eastern_caribbean_dollar_kn.grouping_places == 3
assert eastern_caribbean_dollar_kn.grouping_sign == ','
assert not eastern_caribbean_dollar_kn.international
assert eastern_caribbean_dollar_kn.symbol == '$'
assert eastern_caribbean_dollar_kn.symbol_ahead
assert eastern_caribbean_dollar_kn.symbol_separator == ''
assert eastern_caribbean_dollar_kn.localized_symbol == 'KN$'
assert eastern_caribbean_dollar_kn.convertion == ''
assert eastern_caribbean_dollar_kn.__hash__() == hash(
(eastern_caribbean_dollar_kn.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_kn.__repr__() == (
'EasternCaribbeanDollarKN(amount: 0.1428571428571428571428571429, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "KN$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar_kn.__str__() == '$0.14'
def test_eastern_caribbean_dollar_kn_negative(self):
"""test_eastern_caribbean_dollar_kn_negative."""
amount = -100
eastern_caribbean_dollar_kn = EasternCaribbeanDollarKN(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_kn.numeric_code == '951'
assert eastern_caribbean_dollar_kn.alpha_code == 'XCD'
assert eastern_caribbean_dollar_kn.decimal_places == 2
assert eastern_caribbean_dollar_kn.decimal_sign == '.'
assert eastern_caribbean_dollar_kn.grouping_places == 3
assert eastern_caribbean_dollar_kn.grouping_sign == ','
assert not eastern_caribbean_dollar_kn.international
assert eastern_caribbean_dollar_kn.symbol == '$'
assert eastern_caribbean_dollar_kn.symbol_ahead
assert eastern_caribbean_dollar_kn.symbol_separator == ''
assert eastern_caribbean_dollar_kn.localized_symbol == 'KN$'
assert eastern_caribbean_dollar_kn.convertion == ''
assert eastern_caribbean_dollar_kn.__hash__() == hash(
(eastern_caribbean_dollar_kn.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_kn.__repr__() == (
'EasternCaribbeanDollarKN(amount: -100, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "KN$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar_kn.__str__() == '$-100.00'
def test_eastern_caribbean_dollar_kn_custom(self):
"""test_eastern_caribbean_dollar_kn_custom."""
amount = 1000
eastern_caribbean_dollar_kn = EasternCaribbeanDollarKN(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_kn.amount == decimal
assert eastern_caribbean_dollar_kn.numeric_code == '951'
assert eastern_caribbean_dollar_kn.alpha_code == 'XCD'
assert eastern_caribbean_dollar_kn.decimal_places == 5
assert eastern_caribbean_dollar_kn.decimal_sign == ','
assert eastern_caribbean_dollar_kn.grouping_places == 2
assert eastern_caribbean_dollar_kn.grouping_sign == '.'
assert eastern_caribbean_dollar_kn.international
assert eastern_caribbean_dollar_kn.symbol == '$'
assert not eastern_caribbean_dollar_kn.symbol_ahead
assert eastern_caribbean_dollar_kn.symbol_separator == '_'
assert eastern_caribbean_dollar_kn.localized_symbol == 'KN$'
assert eastern_caribbean_dollar_kn.convertion == ''
assert eastern_caribbean_dollar_kn.__hash__() == hash(
(eastern_caribbean_dollar_kn.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_kn.__repr__() == (
'EasternCaribbeanDollarKN(amount: 1000, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "KN$", '
'numeric_code: "951", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert eastern_caribbean_dollar_kn.__str__() == 'XCD 10,00.00000'
def test_eastern_caribbean_dollar_kn_changed(self):
"""test_ceastern_caribbean_dollar_kn_changed."""
eastern_caribbean_dollar_kn = EasternCaribbeanDollarKN(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_kn.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_kn.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_kn.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_kn.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_kn.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_kn.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_kn.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_kn.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_kn.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_kn.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_kn.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_kn.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_kn.international = True
def test_eastern_caribbean_dollar_kn_math_add(self):
"""test_eastern_caribbean_dollar_kn_math_add."""
eastern_caribbean_dollar_kn_one = EasternCaribbeanDollarKN(amount=1)
eastern_caribbean_dollar_kn_two = EasternCaribbeanDollarKN(amount=2)
eastern_caribbean_dollar_kn_three = EasternCaribbeanDollarKN(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency XCD and OTHER.'):
_ = eastern_caribbean_dollar_kn_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.EasternCaribbeanDollarKN\'> '
'and <class \'str\'>.')):
_ = eastern_caribbean_dollar_kn_one.__add__('1.00')
assert (
eastern_caribbean_dollar_kn_one +
eastern_caribbean_dollar_kn_two) == eastern_caribbean_dollar_kn_three
def test_eastern_caribbean_dollar_kn_slots(self):
"""test_eastern_caribbean_dollar_kn_slots."""
eastern_caribbean_dollar_kn = EasternCaribbeanDollarKN(amount=1000)
with raises(
AttributeError,
match=(
'\'EasternCaribbeanDollarKN\' '
'object has no attribute \'new_variable\'')):
eastern_caribbean_dollar_kn.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Eastern Caribbean Dollar LC representation."""
from multicurrency import EasternCaribbeanDollarLC
class TestEasternCaribbeanDollarLC:
"""EasternCaribbeanDollarLC currency tests."""
def test_eastern_caribbean_dollar_lc(self):
"""test_eastern_caribbean_dollar_lc."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
eastern_caribbean_dollar_lc = EasternCaribbeanDollarLC(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_lc.amount == decimal
assert eastern_caribbean_dollar_lc.numeric_code == '951'
assert eastern_caribbean_dollar_lc.alpha_code == 'XCD'
assert eastern_caribbean_dollar_lc.decimal_places == 2
assert eastern_caribbean_dollar_lc.decimal_sign == '.'
assert eastern_caribbean_dollar_lc.grouping_places == 3
assert eastern_caribbean_dollar_lc.grouping_sign == ','
assert not eastern_caribbean_dollar_lc.international
assert eastern_caribbean_dollar_lc.symbol == '$'
assert eastern_caribbean_dollar_lc.symbol_ahead
assert eastern_caribbean_dollar_lc.symbol_separator == ''
assert eastern_caribbean_dollar_lc.localized_symbol == 'LC$'
assert eastern_caribbean_dollar_lc.convertion == ''
assert eastern_caribbean_dollar_lc.__hash__() == hash(
(eastern_caribbean_dollar_lc.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_lc.__repr__() == (
'EasternCaribbeanDollarLC(amount: 0.1428571428571428571428571429, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "LC$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar_lc.__str__() == '$0.14'
def test_eastern_caribbean_dollar_lc_negative(self):
"""test_eastern_caribbean_dollar_lc_negative."""
amount = -100
eastern_caribbean_dollar_lc = EasternCaribbeanDollarLC(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_lc.numeric_code == '951'
assert eastern_caribbean_dollar_lc.alpha_code == 'XCD'
assert eastern_caribbean_dollar_lc.decimal_places == 2
assert eastern_caribbean_dollar_lc.decimal_sign == '.'
assert eastern_caribbean_dollar_lc.grouping_places == 3
assert eastern_caribbean_dollar_lc.grouping_sign == ','
assert not eastern_caribbean_dollar_lc.international
assert eastern_caribbean_dollar_lc.symbol == '$'
assert eastern_caribbean_dollar_lc.symbol_ahead
assert eastern_caribbean_dollar_lc.symbol_separator == ''
assert eastern_caribbean_dollar_lc.localized_symbol == 'LC$'
assert eastern_caribbean_dollar_lc.convertion == ''
assert eastern_caribbean_dollar_lc.__hash__() == hash(
(eastern_caribbean_dollar_lc.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_lc.__repr__() == (
'EasternCaribbeanDollarLC(amount: -100, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "LC$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar_lc.__str__() == '$-100.00'
def test_eastern_caribbean_dollar_lc_custom(self):
"""test_eastern_caribbean_dollar_lc_custom."""
amount = 1000
eastern_caribbean_dollar_lc = EasternCaribbeanDollarLC(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_lc.amount == decimal
assert eastern_caribbean_dollar_lc.numeric_code == '951'
assert eastern_caribbean_dollar_lc.alpha_code == 'XCD'
assert eastern_caribbean_dollar_lc.decimal_places == 5
assert eastern_caribbean_dollar_lc.decimal_sign == ','
assert eastern_caribbean_dollar_lc.grouping_places == 2
assert eastern_caribbean_dollar_lc.grouping_sign == '.'
assert eastern_caribbean_dollar_lc.international
assert eastern_caribbean_dollar_lc.symbol == '$'
assert not eastern_caribbean_dollar_lc.symbol_ahead
assert eastern_caribbean_dollar_lc.symbol_separator == '_'
assert eastern_caribbean_dollar_lc.localized_symbol == 'LC$'
assert eastern_caribbean_dollar_lc.convertion == ''
assert eastern_caribbean_dollar_lc.__hash__() == hash(
(eastern_caribbean_dollar_lc.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_lc.__repr__() == (
'EasternCaribbeanDollarLC(amount: 1000, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "LC$", '
'numeric_code: "951", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert eastern_caribbean_dollar_lc.__str__() == 'XCD 10,00.00000'
def test_eastern_caribbean_dollar_lc_changed(self):
"""test_ceastern_caribbean_dollar_lc_changed."""
eastern_caribbean_dollar_lc = EasternCaribbeanDollarLC(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_lc.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_lc.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_lc.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_lc.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_lc.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_lc.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_lc.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_lc.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_lc.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_lc.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_lc.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_lc.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_lc.international = True
def test_eastern_caribbean_dollar_lc_math_add(self):
"""test_eastern_caribbean_dollar_lc_math_add."""
eastern_caribbean_dollar_lc_one = EasternCaribbeanDollarLC(amount=1)
eastern_caribbean_dollar_lc_two = EasternCaribbeanDollarLC(amount=2)
eastern_caribbean_dollar_lc_three = EasternCaribbeanDollarLC(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency XCD and OTHER.'):
_ = eastern_caribbean_dollar_lc_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.EasternCaribbeanDollarLC\'> '
'and <class \'str\'>.')):
_ = eastern_caribbean_dollar_lc_one.__add__('1.00')
assert (
eastern_caribbean_dollar_lc_one +
eastern_caribbean_dollar_lc_two) == eastern_caribbean_dollar_lc_three
def test_eastern_caribbean_dollar_lc_slots(self):
"""test_eastern_caribbean_dollar_lc_slots."""
eastern_caribbean_dollar_lc = EasternCaribbeanDollarLC(amount=1000)
with raises(
AttributeError,
match=(
'\'EasternCaribbeanDollarLC\' '
'object has no attribute \'new_variable\'')):
eastern_caribbean_dollar_lc.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Eastern Caribbean Dollar VC representation."""
from multicurrency import EasternCaribbeanDollarVC
class TestEasternCaribbeanDollarVC:
"""EasternCaribbeanDollarVC currency tests."""
def test_eastern_caribbean_dollar_vc(self):
"""test_eastern_caribbean_dollar_vc."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
eastern_caribbean_dollar_vc = EasternCaribbeanDollarVC(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_vc.amount == decimal
assert eastern_caribbean_dollar_vc.numeric_code == '951'
assert eastern_caribbean_dollar_vc.alpha_code == 'XCD'
assert eastern_caribbean_dollar_vc.decimal_places == 2
assert eastern_caribbean_dollar_vc.decimal_sign == '.'
assert eastern_caribbean_dollar_vc.grouping_places == 3
assert eastern_caribbean_dollar_vc.grouping_sign == ','
assert not eastern_caribbean_dollar_vc.international
assert eastern_caribbean_dollar_vc.symbol == '$'
assert eastern_caribbean_dollar_vc.symbol_ahead
assert eastern_caribbean_dollar_vc.symbol_separator == ''
assert eastern_caribbean_dollar_vc.localized_symbol == 'VC$'
assert eastern_caribbean_dollar_vc.convertion == ''
assert eastern_caribbean_dollar_vc.__hash__() == hash(
(eastern_caribbean_dollar_vc.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_vc.__repr__() == (
'EasternCaribbeanDollarVC(amount: 0.1428571428571428571428571429, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "VC$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar_vc.__str__() == '$0.14'
def test_eastern_caribbean_dollar_vc_negative(self):
"""test_eastern_caribbean_dollar_vc_negative."""
amount = -100
eastern_caribbean_dollar_vc = EasternCaribbeanDollarVC(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_vc.numeric_code == '951'
assert eastern_caribbean_dollar_vc.alpha_code == 'XCD'
assert eastern_caribbean_dollar_vc.decimal_places == 2
assert eastern_caribbean_dollar_vc.decimal_sign == '.'
assert eastern_caribbean_dollar_vc.grouping_places == 3
assert eastern_caribbean_dollar_vc.grouping_sign == ','
assert not eastern_caribbean_dollar_vc.international
assert eastern_caribbean_dollar_vc.symbol == '$'
assert eastern_caribbean_dollar_vc.symbol_ahead
assert eastern_caribbean_dollar_vc.symbol_separator == ''
assert eastern_caribbean_dollar_vc.localized_symbol == 'VC$'
assert eastern_caribbean_dollar_vc.convertion == ''
assert eastern_caribbean_dollar_vc.__hash__() == hash(
(eastern_caribbean_dollar_vc.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_vc.__repr__() == (
'EasternCaribbeanDollarVC(amount: -100, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "", '
'localized_symbol: "VC$", '
'numeric_code: "951", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert eastern_caribbean_dollar_vc.__str__() == '$-100.00'
def test_eastern_caribbean_dollar_vc_custom(self):
"""test_eastern_caribbean_dollar_vc_custom."""
amount = 1000
eastern_caribbean_dollar_vc = EasternCaribbeanDollarVC(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert eastern_caribbean_dollar_vc.amount == decimal
assert eastern_caribbean_dollar_vc.numeric_code == '951'
assert eastern_caribbean_dollar_vc.alpha_code == 'XCD'
assert eastern_caribbean_dollar_vc.decimal_places == 5
assert eastern_caribbean_dollar_vc.decimal_sign == ','
assert eastern_caribbean_dollar_vc.grouping_places == 2
assert eastern_caribbean_dollar_vc.grouping_sign == '.'
assert eastern_caribbean_dollar_vc.international
assert eastern_caribbean_dollar_vc.symbol == '$'
assert not eastern_caribbean_dollar_vc.symbol_ahead
assert eastern_caribbean_dollar_vc.symbol_separator == '_'
assert eastern_caribbean_dollar_vc.localized_symbol == 'VC$'
assert eastern_caribbean_dollar_vc.convertion == ''
assert eastern_caribbean_dollar_vc.__hash__() == hash(
(eastern_caribbean_dollar_vc.__class__, decimal, 'XCD', '951'))
assert eastern_caribbean_dollar_vc.__repr__() == (
'EasternCaribbeanDollarVC(amount: 1000, '
'alpha_code: "XCD", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "VC$", '
'numeric_code: "951", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert eastern_caribbean_dollar_vc.__str__() == 'XCD 10,00.00000'
def test_eastern_caribbean_dollar_vc_changed(self):
"""test_ceastern_caribbean_dollar_vc_changed."""
eastern_caribbean_dollar_vc = EasternCaribbeanDollarVC(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_vc.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_vc.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_vc.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_vc.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_vc.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_vc.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_vc.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_vc.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_vc.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_vc.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_vc.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_vc.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
eastern_caribbean_dollar_vc.international = True
def test_eastern_caribbean_dollar_vc_math_add(self):
"""test_eastern_caribbean_dollar_vc_math_add."""
eastern_caribbean_dollar_vc_one = EasternCaribbeanDollarVC(amount=1)
eastern_caribbean_dollar_vc_two = EasternCaribbeanDollarVC(amount=2)
eastern_caribbean_dollar_vc_three = EasternCaribbeanDollarVC(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency XCD and OTHER.'):
_ = eastern_caribbean_dollar_vc_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.EasternCaribbeanDollarVC\'> '
'and <class \'str\'>.')):
_ = eastern_caribbean_dollar_vc_one.__add__('1.00')
assert (
eastern_caribbean_dollar_vc_one +
eastern_caribbean_dollar_vc_two) == eastern_caribbean_dollar_vc_three
def test_eastern_caribbean_dollar_vc_slots(self):
"""test_eastern_caribbean_dollar_vc_slots."""
eastern_caribbean_dollar_vc = EasternCaribbeanDollarVC(amount=1000)
with raises(
AttributeError,
match=(
'\'EasternCaribbeanDollarVC\' '
'object has no attribute \'new_variable\'')):
eastern_caribbean_dollar_vc.new_variable = 'fail' # pylint: disable=assigning-non-slot
"""Tests for the Zimbabwe Dollar representation."""
from multicurrency import ZimbabweDollar
class TestZimbabweDollar:
"""ZimbabweDollar currency tests."""
def test_zimbabwe_dollar(self):
"""test_zimbabwe_dollar."""
amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
zimbabwe_dollar = ZimbabweDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert zimbabwe_dollar.amount == decimal
assert zimbabwe_dollar.numeric_code == '932'
assert zimbabwe_dollar.alpha_code == 'ZWL'
assert zimbabwe_dollar.decimal_places == 2
assert zimbabwe_dollar.decimal_sign == '.'
assert zimbabwe_dollar.grouping_places == 3
assert zimbabwe_dollar.grouping_sign == ','
assert not zimbabwe_dollar.international
assert zimbabwe_dollar.symbol == '$'
assert zimbabwe_dollar.symbol_ahead
assert zimbabwe_dollar.symbol_separator == '\u00A0'
assert zimbabwe_dollar.localized_symbol == 'ZW$'
assert zimbabwe_dollar.convertion == ''
assert zimbabwe_dollar.__hash__() == hash(
(zimbabwe_dollar.__class__, decimal, 'ZWL', '932'))
assert zimbabwe_dollar.__repr__() == (
'ZimbabweDollar(amount: 0.1428571428571428571428571429, '
'alpha_code: "ZWL", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "\u00A0", '
'localized_symbol: "ZW$", '
'numeric_code: "932", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert zimbabwe_dollar.__str__() == '$ 0.14'
def test_zimbabwe_dollar_negative(self):
"""test_zimbabwe_dollar_negative."""
amount = -100
zimbabwe_dollar = ZimbabweDollar(amount=amount)
decimal = CONTEXT.create_decimal(amount)
assert zimbabwe_dollar.numeric_code == '932'
assert zimbabwe_dollar.alpha_code == 'ZWL'
assert zimbabwe_dollar.decimal_places == 2
assert zimbabwe_dollar.decimal_sign == '.'
assert zimbabwe_dollar.grouping_places == 3
assert zimbabwe_dollar.grouping_sign == ','
assert not zimbabwe_dollar.international
assert zimbabwe_dollar.symbol == '$'
assert zimbabwe_dollar.symbol_ahead
assert zimbabwe_dollar.symbol_separator == '\u00A0'
assert zimbabwe_dollar.localized_symbol == 'ZW$'
assert zimbabwe_dollar.convertion == ''
assert zimbabwe_dollar.__hash__() == hash(
(zimbabwe_dollar.__class__, decimal, 'ZWL', '932'))
assert zimbabwe_dollar.__repr__() == (
'ZimbabweDollar(amount: -100, '
'alpha_code: "ZWL", '
'symbol: "$", '
'symbol_ahead: True, '
'symbol_separator: "\u00A0", '
'localized_symbol: "ZW$", '
'numeric_code: "932", '
'decimal_places: "2", '
'decimal_sign: ".", '
'grouping_places: "3", '
'grouping_sign: ",", '
'convertion: "", '
'international: False)')
assert zimbabwe_dollar.__str__() == '$ -100.00'
def test_zimbabwe_dollar_custom(self):
"""test_zimbabwe_dollar_custom."""
amount = 1000
zimbabwe_dollar = ZimbabweDollar(
amount=amount,
decimal_places=5,
decimal_sign=',',
grouping_places=2,
grouping_sign='.',
international=True,
symbol_ahead=False,
symbol_separator='_')
decimal = CONTEXT.create_decimal(amount)
assert zimbabwe_dollar.amount == decimal
assert zimbabwe_dollar.numeric_code == '932'
assert zimbabwe_dollar.alpha_code == 'ZWL'
assert zimbabwe_dollar.decimal_places == 5
assert zimbabwe_dollar.decimal_sign == ','
assert zimbabwe_dollar.grouping_places == 2
assert zimbabwe_dollar.grouping_sign == '.'
assert zimbabwe_dollar.international
assert zimbabwe_dollar.symbol == '$'
assert not zimbabwe_dollar.symbol_ahead
assert zimbabwe_dollar.symbol_separator == '_'
assert zimbabwe_dollar.localized_symbol == 'ZW$'
assert zimbabwe_dollar.convertion == ''
assert zimbabwe_dollar.__hash__() == hash(
(zimbabwe_dollar.__class__, decimal, 'ZWL', '932'))
assert zimbabwe_dollar.__repr__() == (
'ZimbabweDollar(amount: 1000, '
'alpha_code: "ZWL", '
'symbol: "$", '
'symbol_ahead: False, '
'symbol_separator: "_", '
'localized_symbol: "ZW$", '
'numeric_code: "932", '
'decimal_places: "5", '
'decimal_sign: ",", '
'grouping_places: "2", '
'grouping_sign: ".", '
'convertion: "", '
'international: True)')
assert zimbabwe_dollar.__str__() == 'ZWL 10,00.00000'
def test_zimbabwe_dollar_changed(self):
"""test_czimbabwe_dollar_changed."""
zimbabwe_dollar = ZimbabweDollar(amount=1000)
with raises(
AttributeError,
match='can\'t set attribute'):
zimbabwe_dollar.amount = 999
with raises(
AttributeError,
match='can\'t set attribute'):
zimbabwe_dollar.alpha_code = 'EUR'
with raises(
AttributeError,
match='can\'t set attribute'):
zimbabwe_dollar.convertion = '0123456789,.'
with raises(
AttributeError,
match='can\'t set attribute'):
zimbabwe_dollar.symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
zimbabwe_dollar.symbol_ahead = False
with raises(
AttributeError,
match='can\'t set attribute'):
zimbabwe_dollar.symbol_separator = '_'
with raises(
AttributeError,
match='can\'t set attribute'):
zimbabwe_dollar.localized_symbol = '€'
with raises(
AttributeError,
match='can\'t set attribute'):
zimbabwe_dollar.numeric_code = '978'
with raises(
AttributeError,
match='can\'t set attribute'):
zimbabwe_dollar.decimal_places = 3
with raises(
AttributeError,
match='can\'t set attribute'):
zimbabwe_dollar.decimal_sign = ','
with raises(
AttributeError,
match='can\'t set attribute'):
zimbabwe_dollar.grouping_places = 4
with raises(
AttributeError,
match='can\'t set attribute'):
zimbabwe_dollar.grouping_sign = '.'
with raises(
AttributeError,
match='can\'t set attribute'):
zimbabwe_dollar.international = True
def test_zimbabwe_dollar_math_add(self):
"""test_zimbabwe_dollar_math_add."""
zimbabwe_dollar_one = ZimbabweDollar(amount=1)
zimbabwe_dollar_two = ZimbabweDollar(amount=2)
zimbabwe_dollar_three = ZimbabweDollar(amount=3)
currency = Currency(amount=1, alpha_code='OTHER')
with raises(
CurrencyMismatchException,
match='unsupported operation between currency ZWL and OTHER.'):
_ = zimbabwe_dollar_one + currency
with raises(
CurrencyTypeException,
match=(
'unsupported operation between <class \'multicurrency.'
'dollar.ZimbabweDollar\'> '
'and <class \'str\'>.')):
_ = zimbabwe_dollar_one.__add__('1.00')
assert (
zimbabwe_dollar_one +
zimbabwe_dollar_two) == zimbabwe_dollar_three
def test_zimbabwe_dollar_slots(self):
"""test_zimbabwe_dollar_slots."""
zimbabwe_dollar = ZimbabweDollar(amount=1000)
with raises(
AttributeError,
match=(
'\'ZimbabweDollar\' '
'object has no attribute \'new_variable\'')):
zimbabwe_dollar.new_variable = 'fail' # pylint: disable=assigning-non-slot
|
snumrl/DataDrivenBipedController
|
PyCommon/external_libraries/VirtualPhysics/vpLib/include/VP/vpNDOFJoint.inl
|
<reponame>snumrl/DataDrivenBipedController
/*
VirtualPhysics v0.9
2008.Feb.21
Imaging Media Research Center, KIST
<EMAIL>
*/
VP_INLINE void vpNDOFJoint::SetTransformFunc(TransformNDOF *fun)
{
assert(m_iDOF == fun->m_iDOF && "vpNDOFJoint::SetTransformFunc(TransformNDOF *) -> inconsistent DOF");
m_pTransform = fun;
}
VP_INLINE void vpNDOFJoint::SetPosition(int i, const scalar &x)
{
m_rQ[i] = (m_eSign == VP::PLUS ? x : -x);
}
VP_INLINE void vpNDOFJoint::SetVelocity(int i, const scalar &x)
{
m_rDq[i] = (m_eSign == VP::PLUS ? x : -x);
}
VP_INLINE void vpNDOFJoint::SetAcceleration(int i, const scalar &x)
{
m_rDdq[i] = (m_eSign == VP::PLUS ? x : -x);
}
VP_INLINE void vpNDOFJoint::SetTorque(int i, const scalar &x)
{
m_rActuationTau[i] = (m_eSign == VP::PLUS ? x : -x);
}
VP_INLINE void vpNDOFJoint::AddTorque(int i, const scalar &x)
{
m_rActuationTau[i] += (m_eSign == VP::PLUS ? x : -x);
}
VP_INLINE void vpNDOFJoint::SetInitialPosition(int i, const scalar &x)
{
m_rQi[i] = (m_eSign == VP::PLUS ? x : -x);
}
VP_INLINE void vpNDOFJoint::SetElasticity(int i, const scalar &x)
{
assert(x >= SCALAR_0 && "vpNDOFJoint::SetElasticity(scalar) -> can not be negative");
m_rK[i] = x;
}
VP_INLINE void vpNDOFJoint::SetDamping(int i, const scalar &x)
{
assert(x >= SCALAR_0 && "vpNDOFJoint::SetDamping(scalar) -> can not be negative");
m_rC[i] = x;
}
VP_INLINE void vpNDOFJoint::SetUpperLimit(int i, const scalar &x)
{
m_bHasUpperLimit[i] = true;
m_rQul[i] = (m_eSign == VP::PLUS ? x : -x);
}
VP_INLINE void vpNDOFJoint::SetLowerLimit(int i, const scalar &x)
{
m_bHasLowerLimit[i] = true;
m_rQll[i] = (m_eSign == VP::PLUS ? x : -x);
}
VP_INLINE void vpNDOFJoint::DisableUpperLimit(int i)
{
m_bHasUpperLimit[i] = false;
}
VP_INLINE void vpNDOFJoint::DisableLowerLimit(int i)
{
m_bHasLowerLimit[i] = false;
}
VP_INLINE void vpNDOFJoint::SetRestitution(int i, const scalar &e)
{
m_rRestitution[i] = e;
}
VP_INLINE scalar vpNDOFJoint::GetPosition(int i) const
{
return (m_eSign == VP::PLUS ? m_rQ[i]: -m_rQ[i]);
}
VP_INLINE scalar vpNDOFJoint::GetVelocity(int i) const
{
return (m_eSign == VP::PLUS ? m_rDq[i]: -m_rDq[i]);
}
VP_INLINE scalar vpNDOFJoint::GetAcceleration(int i) const
{
return (m_eSign == VP::PLUS ? m_rDdq[i]: -m_rDdq[i]);
}
VP_INLINE scalar vpNDOFJoint::GetTorque(int i) const
{
return (m_eSign == VP::PLUS ? m_rActuationTau[i]: -m_rActuationTau[i]);
}
VP_INLINE scalar vpNDOFJoint::GetInitialPosition(int i) const
{
return (m_eSign == VP::PLUS ? m_rQi[i]: -m_rQi[i]);
}
VP_INLINE const scalar &vpNDOFJoint::GetElasticity(int i) const
{
return m_rK[i];
}
VP_INLINE const scalar &vpNDOFJoint::GetDamping(int i) const
{
return m_rC[i];
}
VP_INLINE int vpNDOFJoint::GetDOF(void) const
{
return m_iDOF;
}
VP_INLINE SE3 vpNDOFJoint::Transform(void) const
{
assert(m_pTransform && "vpNDOFJoint::Transform -> transform function is not defined");
return m_pTransform->GetTransform(m_rQ);
}
VP_INLINE void vpNDOFJoint::UpdateSpringDamperTorque(void)
{
for ( int i = 0; i < m_iDOF; i++ ) m_rSpringDamperTau[i] = m_rK[i] * (m_rQ[i] - m_rQi[i]) + m_rC[i] * m_rDq[i];
}
VP_INLINE scalar vpNDOFJoint::GetPotentialEnergy(void) const
{
scalar sum = SCALAR_0;
for ( int i = 0; i < m_iDOF; i++ ) sum += m_rK[i] * (m_rQ[i] - m_rQi[i]) * (m_rQ[i] - m_rQi[i]);
return SCALAR_1_2 * sum;
}
VP_INLINE scalar vpNDOFJoint::GetNormalForce(void) const
{
return SCALAR_0;
}
VP_INLINE scalar vpNDOFJoint::GetNormalTorque(void) const
{
return SCALAR_0;
}
VP_INLINE void vpNDOFJoint::SetDisplacement_(int i, const scalar &x)
{
m_rQ[i] = x;
}
VP_INLINE const scalar &vpNDOFJoint::GetDisplacement_(int i) const
{
return m_rQ[i];
}
VP_INLINE void vpNDOFJoint::SetVelocity_(int i, const scalar &x)
{
m_rDq[i] = x;
}
VP_INLINE const scalar &vpNDOFJoint::GetVelocity_(int i) const
{
return m_rDq[i];
}
VP_INLINE void vpNDOFJoint::SetAcceleration_(int i, const scalar &x)
{
m_rDdq[i] = x;
}
VP_INLINE const scalar &vpNDOFJoint::GetAcceleration_(int i) const
{
return m_rDdq[i];
}
VP_INLINE void vpNDOFJoint::SetImpulsiveTorque_(int i, const scalar &x)
{
m_rImpulsiveTau[i] = x;
}
VP_INLINE const scalar &vpNDOFJoint::GetImpulsiveTorque_(int i) const
{
return m_rImpulsiveTau[i];
}
VP_INLINE void vpNDOFJoint::SetSpringDamperTorque_(int i, const scalar &x)
{
m_rSpringDamperTau[i] = x;
}
VP_INLINE void vpNDOFJoint::SetTorque_(int i, const scalar &x)
{
m_rActuationTau[i] = x;
}
VP_INLINE scalar vpNDOFJoint::GetTorque_(int i) const
{
return (m_rActuationTau[i] - m_rSpringDamperTau[i]);
}
VP_INLINE const scalar &vpNDOFJoint::GetRestitution_(int i) const
{
return m_rRestitution[i];
}
VP_INLINE bool vpNDOFJoint::ViolateUpperLimit_(int i) const
{
return m_bHasUpperLimit[i] && m_rQ[i] >= m_rQul[i];
}
VP_INLINE bool vpNDOFJoint::ViolateLowerLimit_(int i) const
{
return m_bHasLowerLimit[i] && m_rQ[i] <= m_rQll[i];
}
VP_INLINE TransformNDOF::TransformNDOF(int dof)
{
m_iDOF = dof;
m_rEPS = LIE_EPS;
}
VP_INLINE bool vpNDOFJoint::IsEnabledUpperLimit(int idx) const
{
return m_bHasUpperLimit[idx];
}
VP_INLINE bool vpNDOFJoint::IsEnabledLowerLimit(int idx) const
{
return m_bHasLowerLimit[idx];
}
VP_INLINE void vpNDOFJoint::IntegrateDisplacement(const scalar &h)
{
for ( int i = 0; i < m_iDOF; i++ ) m_rQ[i] += h * m_rDq[i];
}
VP_INLINE void vpNDOFJoint::IntegrateVelocity(const scalar &h)
{
for ( int i = 0; i < m_iDOF; i++ ) m_rDq[i] += h * m_rDdq[i];
}
|
TU-Berlin-DIMA/babelfish
|
compiler/src/main/java/de/tub/dima/babelfish/typesytem/valueTypes/number/integer/CSVSourceInt_32.java
|
package de.tub.dima.babelfish.typesytem.valueTypes.number.integer;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.library.ExportLibrary;
import com.oracle.truffle.api.library.ExportMessage;
import de.tub.dima.babelfish.storage.UnsafeUtils;
@ExportLibrary(value = IntLibrary.class)
public class CSVSourceInt_32 extends Int_32 {
private final long startPosition;
private final long endPosition;
private int cachedValue;
public boolean cached;
public CSVSourceInt_32(long startPosition, long endPosition) {
this.startPosition = startPosition;
this.endPosition = endPosition;
}
@Override
public int asInt() {
int resultValue = 0;
for (long position = startPosition; position < endPosition; position++) {
byte value = UnsafeUtils.getByte(position);
int charValue = value - '0';
resultValue = resultValue * 10 + charValue;
}
cachedValue = (short) resultValue;
cached = true;
return (short) resultValue;
}
@ExportMessage
public static class asIntValue{
@Specialization(guards = "value.cached")
public static int asIntCached(CSVSourceInt_32 value){
return value.cachedValue;
}
@Specialization()
public static int asInt(CSVSourceInt_32 value){
return value.asInt();
}
}
}
|
kjerabek/netexp
|
netexp/info_extractors/tcpip_flow_extractor.py
|
<gh_stars>0
from netexp.info_extractors.base_extractor import BaseExtractor
from netexp.primitives.packet.base_tcpip_packet_info import BaseTCPIPPacketInfo
class TcpIpFlowExtractor(BaseExtractor):
def __init__(self, config):
self.config = config
self.flows = {}
self.unfinished_flows = []
self.finished_flows = []
self.last_timestamp = 0
self.time_range_unfinished = config.flow_time_range * 1000000
self.Flow = config.which_flow
def process_packet(self, timestamp, packet):
packet_info = self.Flow.which_packet(timestamp, packet)
self.last_timestamp = packet_info.timestamp
if packet_info.proto == 'TCP':
self.__add_packet(packet_info)
def __add_packet(self, packet_info: BaseTCPIPPacketInfo):
if self.__is_new_flow_start(packet_info):
self.__finish_flow_if_already_exists(packet_info)
self.__add_new_flow(packet_info)
else:
self.__add_packet_to_existing_flow(packet_info)
self.__finish_unfinished_flows()
@staticmethod
def __is_new_flow_start(packet_info: BaseTCPIPPacketInfo) -> bool:
return packet_info.tcp_flag_syn == 1 and packet_info.tcp_flag_ack == 0
def __finish_flow_if_already_exists(self, packet_info: BaseTCPIPPacketInfo):
if packet_info.flow_key in self.flows.keys():
finished_flow = self.flows.pop(packet_info.flow_key)
self.finished_flows.append(finished_flow)
def __add_new_flow(self, packet_info: BaseTCPIPPacketInfo):
flow = self.Flow(packet_info, self.config)
self.flows[packet_info.flow_key] = flow
def __add_packet_to_existing_flow(self, packet_info: BaseTCPIPPacketInfo):
if packet_info.flow_key in self.flows.keys():
self.__add_packet_to_flows(packet_info)
else:
self.__add_packet_to_unfinished_flows(packet_info)
def __finish_unfinished_flows(self):
if len(self.unfinished_flows) == 0:
return
index = 0
while index < len(self.unfinished_flows):
if (self.last_timestamp - self.unfinished_flows[index].last_packet_timestamp) > self.time_range_unfinished:
finished_flow = self.unfinished_flows.pop(index)
self.finished_flows.append(finished_flow)
index -= 1
else:
break
index += 1
def __add_packet_to_flows(self, packet_info: BaseTCPIPPacketInfo):
flow = self.flows[packet_info.flow_key]
flow.add_packet(packet_info)
if flow.complete:
unfinished_flow = self.flows.pop(packet_info.flow_key)
self.unfinished_flows.append(unfinished_flow)
def __add_packet_to_unfinished_flows(self, packet_info: BaseTCPIPPacketInfo):
for index in range(0, len(self.unfinished_flows), -1):
if self.unfinished_flows[index].flow_key == packet_info.flow_key:
unfinished_flow = self.unfinished_flows.pop(index)
unfinished_flow.add_packet(packet_info)
self.unfinished_flows.append(unfinished_flow)
break
def pop_processed(self):
finished_flows = [flow for flow in self.finished_flows]
self.finished_flows.clear()
return finished_flows
def pop_rest(self):
rest = [self.flows[key] for key in self.flows.keys()]
rest.extend(self.unfinished_flows)
rest.extend(self.finished_flows)
self.flows.clear()
self.unfinished_flows.clear()
self.finished_flows.clear()
return rest
|
Ding-Jun/ReportSystem
|
src/main/java/com/funtest/analysis/dao/impl/UserDaoImpl.java
|
<reponame>Ding-Jun/ReportSystem
package com.funtest.analysis.dao.impl;
import java.math.BigInteger;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Repository;
import com.funtest.analysis.bean.User;
import com.funtest.analysis.dao.BaseDao;
import com.funtest.analysis.dao.UserDao;
import com.funtest.core.bean.page.Page;
import com.funtest.core.bean.page.PageCondition;
@Repository
public class UserDaoImpl extends BaseDao<User> implements UserDao{
private static final String QUERY_USER_RECORDS="SELECT count(*) FROM `t_user` WHERE 1=1 ";
private static final String QUERY_USER_PAGE="SELECT * FROM `t_user` WHERE 1=1 ";
private static final String QUERY_USER_BY_NAME="SELECT * FROM `t_user` WHERE 1=1 AND `name`=? ";
private static final String QUERY_USER_BY_EMPLOYEE_ID="SELECT * FROM `t_user` WHERE 1=1 AND `employeeId`=? ";
private static final String QUERY_USER_BY_PHONE_NO="SELECT * FROM `t_user` WHERE 1=1 AND `phoneNo`=? ";
@Override
public Integer createUser(User User) {
return super.create(User);
}
@Override
public void deleteUser(User User) {
super.delete(User);
}
@Override
public void updateUser(User User) {
super.update(User);
}
@Override
public User queryUser(Integer id) {
return super.query(id);
}
@Override
public User queryUserByName(String name) {
String sql = QUERY_USER_BY_NAME.replaceFirst("[?]", "'"+name+"'");
SQLQuery query = this.currentSession().createSQLQuery(sql);
return (User) query.addEntity(User.class).uniqueResult();
}
@Override
public BigInteger queryUserRecords() {
SQLQuery query = this.currentSession().createSQLQuery(QUERY_USER_RECORDS);
return (BigInteger) query.uniqueResult();
}
@SuppressWarnings("unchecked")
@Override
public Page<User> queryPage(Page<User> page, PageCondition pageCondition) {
SQLQuery query = this.currentSession().createSQLQuery(QUERY_USER_PAGE);
//页码从1开始
query.setFirstResult((page.getCurPage()-1)*page.getPageSize());
query.setMaxResults(page.getPageSize());
page.setRowData(query.addEntity(User.class).list());
return page;
}
@Override
public User queryUserByEmployeeId(String employeeId) {
String sql = QUERY_USER_BY_EMPLOYEE_ID.replaceFirst("[?]", "'"+employeeId+"'");
SQLQuery query = this.currentSession().createSQLQuery(sql);
return (User) query.addEntity(User.class).uniqueResult();
}
@Override
public User queryUserByPhoneNo(String phoneNo) {
String sql = QUERY_USER_BY_PHONE_NO.replaceFirst("[?]", "'"+phoneNo+"'");
SQLQuery query = this.currentSession().createSQLQuery(sql);
return (User) query.addEntity(User.class).uniqueResult();
}
}
|
yjy239/SuperJsBridge
|
app/src/main/java/com/yjy/superjsbridgedemo/model/User.java
|
package com.yjy.superjsbridgedemo.model;
/**
* <pre>
* author : yjy
* e-mail : <EMAIL>
* time : 2020/08/06
* desc :
* version: 1.0
* </pre>
*/
public class User {
String username;
String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
jas07061002/TweetMiner_Summer
|
app/models/Tweet_Object.java
|
<reponame>jas07061002/TweetMiner_Summer
package models;
/**
* Retrieves a tweet_object, which fetches tweet details like created date,
* full text , tweet id, User details from JSON response of Twitter API.
*
* @author <NAME>
* @version 1.0.0
*/
public class Tweet_Object {
/**
* Tweet created date in string format.
*/
public String created_at;
/**
* Full text in string format.
*/
public String full_text;
/**
* User information in user object
*/
public User_Object user;
/**
* Entity information like hashtags in entities object .
*/
public Entity_Object entities;
/**
* Twitter id in string format.
*/
public String id;
/**
* Geo code information like latitude and longitude in geo object .
*/
public Geo_Object geo;
/**
* Word count in long format.
*/
public Long WordStat;
}
|
gta-chaos-mod/plugin-sdk
|
plugin_III/game_III/CRegisteredShinyText.cpp
|
<filename>plugin_III/game_III/CRegisteredShinyText.cpp<gh_stars>100-1000
/*
Plugin-SDK (Grand Theft Auto 3) source file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#include "CRegisteredShinyText.h"
PLUGIN_SOURCE_FILE
int ctor_addr(CRegisteredShinyText) = ADDRESS_BY_VERSION(0x51C330, 0x51C560, 0x51C4F0);
int ctor_gaddr(CRegisteredShinyText) = GLOBAL_ADDRESS_BY_VERSION(0x51C330, 0x51C560, 0x51C4F0);
|
ivan-uskov/graphics
|
3d_walk/utils/rangef.h
|
<gh_stars>0
#pragma once
class RangeF
{
public:
RangeF(float from, float to);
bool has(float num) const;
private:
float m_from = 0;
float m_to = 0;
};
|
jb892/sstk
|
client/js/lib/STK.js
|
// Include everything in STK-core
var STK = require('./STK-core');
STK.Constants.sys = {
fs: require('io/FileUtil'),
Buffer: Buffer
};
/* List namespaces */
/** @namespace anim */
/** @namespace data */
/** @namespace editor */
/** @namespace nlp */
/** @namespace query */
/** @namespace ui */
// Include additional UI apps and utils
STK.util.assign(STK, {
DataViz: require('./viz/DataVizUI'),
ModelSchema: require('./model/ModelSchema'),
ModelQuerier: require('./query/ModelQuerier'),
ModelViewer: require('./model-viewer/ModelViewer'),
VoxelViewer: require('./model-viewer/VoxelViewer'),
RecordingViewer: require('./interaction-viewer/RecordingViewer'),
ScanSchema: require('./model/ScanSchema'),
ScanQuerier: require('./query/ScanQuerier'),
SceneSchema: require('./scene/SceneSchema'),
SceneViewer: require('./scene-viewer/SceneViewer'),
SceneQuerier: require('./query/SceneQuerier'),
SearchController: require('./search/SearchController'),
SimpleAssetQuerier: require('./query/SimpleAssetQuerier'),
Stats: require('./stats/stats'),
SimpleModelViewer: require('./model-viewer/SimpleModelViewer'),
SimpleModelViewerWithControls: require('./model-viewer/SimpleModelViewerWithControls'),
SimViewer: require('./sim/SimViewer'),
UIUtil: require('./ui/UIUtil'),
FileUtil: require('./io/FileUtil'),
TaxonomyViewer: require('./taxonomy/TaxonomyViewer'),
WordnetTaxonomyDetailsHandler: require('./taxonomy/WordnetTaxonomyDetailsHandler')
});
module.exports = STK;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.