text:
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------

#include "RuntimeLibraryPch.h"

#ifdef ENABLE_WASM
#include "WasmLimits.h"

namespace Js
{

WebAssemblyTable::WebAssemblyTable(Var * values, uint32 currentLength, uint32 initialLength, uint32 maxLength, DynamicType * type) :
    DynamicObject(type),
    m_values((Field(Var)*)values),
    m_currentLength(currentLength),
    m_initialLength(initialLength),
    m_maxLength(maxLength)
{
}

/* static */
bool
WebAssemblyTable::Is(Var value)
{
    return JavascriptOperators::GetTypeId(value) == TypeIds_WebAssemblyTable;
}

/* static */
WebAssemblyTable *
WebAssemblyTable::FromVar(Var value)
{
    AssertOrFailFast(WebAssemblyTable::Is(value));
    return static_cast<WebAssemblyTable*>(value);
}

/* static */
WebAssemblyTable *
WebAssemblyTable::UnsafeFromVar(Var value)
{
    Assert(WebAssemblyTable::Is(value));
    return static_cast<WebAssemblyTable*>(value);
}

Var
WebAssemblyTable::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
{
    PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);

    ARGUMENTS(args, callInfo);
    ScriptContext* scriptContext = function->GetScriptContext();

    AssertMsg(args.HasArg(), "Should always have implicit 'this'");

    Var newTarget = args.GetNewTarget();
    JavascriptOperators::GetAndAssertIsConstructorSuperCall(args);

    if (!(callInfo.Flags & CallFlags_New) || (newTarget && JavascriptOperators::IsUndefinedObject(newTarget)))
    {
        JavascriptError::ThrowTypeError(scriptContext, JSERR_ClassConstructorCannotBeCalledWithoutNew, _u("WebAssembly.Table"));
    }

    if (args.Info.Count < 2 || !JavascriptOperators::IsObject(args[1]))
    {
        JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedObject, _u("tableDescriptor"));
    }
    DynamicObject * tableDescriptor = JavascriptObject::FromVar(args[1]);

    Var elementVar = JavascriptOperators::OP_GetProperty(tableDescriptor, PropertyIds::element, scriptContext);
    if (!JavascriptOperators::StrictEqualString(elementVar, scriptContext->GetLibrary()->CreateStringFromCppLiteral(_u("anyfunc"))))
    {
        JavascriptError::ThrowTypeError(scriptContext, WASMERR_ExpectedAnyFunc, _u("tableDescriptor.element"));
    }

    Var initVar = JavascriptOperators::OP_GetProperty(tableDescriptor, PropertyIds::initial, scriptContext);
    uint32 initial = WebAssembly::ToNonWrappingUint32(initVar, scriptContext);

    uint32 maximum = Wasm::Limits::GetMaxTableSize();
    if (JavascriptOperators::OP_HasProperty(tableDescriptor, PropertyIds::maximum, scriptContext))
    {
        Var maxVar = JavascriptOperators::OP_GetProperty(tableDescriptor, PropertyIds::maximum, scriptContext);
        maximum = WebAssembly::ToNonWrappingUint32(maxVar, scriptContext);
    }
    return Create(initial, maximum, scriptContext);
}

Var
WebAssemblyTable::EntryGetterLength(RecyclableObject* function, CallInfo callInfo, ...)
{
    PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);

    ARGUMENTS(args, callInfo);
    ScriptContext* scriptContext = function->GetScriptContext();

    Assert(!(callInfo.Flags & CallFlags_New));

    if (args.Info.Count == 0 || !WebAssemblyTable::Is(args[0]))
    {
        JavascriptError::ThrowTypeError(scriptContext, WASMERR_NeedTableObject);
    }
    WebAssemblyTable * table = WebAssemblyTable::FromVar(args[0]);
    return JavascriptNumber::ToVar(table->m_currentLength, scriptContext);
}

Var
WebAssemblyTable::EntryGrow(RecyclableObject* function, CallInfo callInfo, ...)
{
    PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);

    ARGUMENTS(args, callInfo);
    ScriptContext* scriptContext = function->GetScriptContext();

    Assert(!(callInfo.Flags & CallFlags_New));

    if (args.Info.Count == 0 || !WebAssemblyTable::Is(args[0]))
    {
        JavascriptError::ThrowTypeError(scriptContext, WASMERR_NeedTableObject);
    }
    WebAssemblyTable * table = WebAssemblyTable::FromVar(args[0]);
    uint32 oldLength = table->m_currentLength;

    Var deltaVar = args.Info.Count >= 2 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
    uint32 delta = WebAssembly::ToNonWrappingUint32(deltaVar, scriptContext);
    if (delta > 0)
    {
        uint32 newLength = 0;
        if (UInt32Math::Add(table->m_currentLength, delta, &newLength) || newLength > table->m_maxLength)
        {
            JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange);
        }

        Field(Var) * newValues = RecyclerNewArrayZ(scriptContext->GetRecycler(), Field(Var), newLength);
        CopyArray(newValues, newLength, table->m_values, table->m_currentLength);

        table->m_values = newValues;
        table->m_currentLength = newLength;
    }

    return JavascriptNumber::ToVar(oldLength, scriptContext);
}

Var
WebAssemblyTable::EntryGet(RecyclableObject* function, CallInfo callInfo, ...)
{
    PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);

    ARGUMENTS(args, callInfo);
    ScriptContext* scriptContext = function->GetScriptContext();

    Assert(!(callInfo.Flags & CallFlags_New));

    if (args.Info.Count == 0 || !WebAssemblyTable::Is(args[0]))
    {
        JavascriptError::ThrowTypeError(scriptContext, WASMERR_NeedTableObject);
    }
    WebAssemblyTable * table = WebAssemblyTable::FromVar(args[0]);

    Var indexVar = scriptContext->GetLibrary()->GetUndefined();
    if (args.Info.Count >= 2)
    {
        indexVar = args[1];
    }
    uint32 index = WebAssembly::ToNonWrappingUint32(indexVar, scriptContext);
    if (index >= table->m_currentLength)
    {
        JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange);
    }
    if (!table->m_values[index])
    {
        return scriptContext->GetLibrary()->GetNull();
    }

    return table->m_values[index];
}

Var
WebAssemblyTable::EntrySet(RecyclableObject* function, CallInfo callInfo, ...)
{
    PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);

    ARGUMENTS(args, callInfo);
    ScriptContext* scriptContext = function->GetScriptContext();

    Assert(!(callInfo.Flags & CallFlags_New));

    if (args.Info.Count == 0 || !WebAssemblyTable::Is(args[0]))
    {
        JavascriptError::ThrowTypeError(scriptContext, WASMERR_NeedTableObject);
    }
    WebAssemblyTable * table = WebAssemblyTable::FromVar(args[0]);

    if (args.Info.Count < 3)
    {
        JavascriptError::ThrowTypeError(scriptContext, WASMERR_NeedWebAssemblyFunc);
    }
    Var indexVar = args[1];
    Var value = args[2];

    if (JavascriptOperators::IsNull(value))
    {
        value = nullptr;
    }
    else if (!WasmScriptFunction::Is(args[2]))
    {
        JavascriptError::ThrowTypeError(scriptContext, WASMERR_NeedWebAssemblyFunc);
    }

    uint32 index = WebAssembly::ToNonWrappingUint32(indexVar, scriptContext);
    if (index >= table->m_currentLength)
    {
        JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange);
    }

    table->m_values[index] = value;

    return scriptContext->GetLibrary()->GetUndefined();
}

WebAssemblyTable *
WebAssemblyTable::Create(uint32 initial, uint32 maximum, ScriptContext * scriptContext)
{
    if (initial > maximum || initial > Wasm::Limits::GetMaxTableSize() || maximum > Wasm::Limits::GetMaxTableSize())
    {
        JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgumentOutOfRange);
    }
    Field(Var) * values = nullptr;
    if (initial > 0)
    {
        values = RecyclerNewArrayZ(scriptContext->GetRecycler(), Field(Var), initial);
    }
    return RecyclerNew(scriptContext->GetRecycler(), WebAssemblyTable, (Var*)values, initial, initial, maximum, scriptContext->GetLibrary()->GetWebAssemblyTableType());
}

void
WebAssemblyTable::DirectSetValue(uint index, Var val)
{
    Assert(index < m_currentLength);
    Assert(!val || WasmScriptFunction::Is(val));
    m_values[index] = val;
}

Var
WebAssemblyTable::DirectGetValue(uint index) const
{
    Assert(index < m_currentLength);
    Var val = m_values[index];
    Assert(!val || WasmScriptFunction::Is(val));
    return val;
}

uint32
WebAssemblyTable::GetCurrentLength() const
{
    return m_currentLength;
}

uint32
WebAssemblyTable::GetInitialLength() const
{
    return m_initialLength;
}

uint32
WebAssemblyTable::GetMaximumLength() const
{
    return m_maxLength;
}

} // namespace Js

#endif // ENABLE_WASM


text:
from yowsup.structs import ProtocolEntity, ProtocolTreeNode
class PresenceProtocolEntity(ProtocolEntity):
    '''
    <presence type="{{type}} name={{push_name}}"></presence>
    Should normally be either type or name

    when contact goes offline:
    <presence type="unavailable" from="{{contact_jid}}" last="deny | ?">
    </presence>

    when contact goes online:
    <presence from="contact_jid">
    </presence>

    '''

    def __init__(self, _type = None, name = None):
        super(PresenceProtocolEntity, self).__init__("presence")
        self._type= _type
        self.name = name

    def getType(self):
        return self._type

    def getName(self):
        return self.name

    def toProtocolTreeNode(self):
        attribs = {}
        if self._type:
            attribs["type"] = self._type

        if self.name:
            attribs["name"] = self.name

        return self._createProtocolTreeNode(attribs, None, None)

    def __str__(self):
        out  = "Presence:\n"
        if self._type:
            out += "Type: %s\n" % self._type

        if self.name:
            out += "Name: %s\n" % self.name
        return out

    @staticmethod
    def fromProtocolTreeNode(node):
        return PresenceProtocolEntity(
            node.getAttributeValue("type"),
            node.getAttributeValue("name")
            )

redpajama_set_name: RedPajamaGithub


text:
package util;

import java.util.Map;

/**
 * Interface for any class that stores and processes vertex attributes Each
 * attribute will have a unique name.
 */
public interface IVertexData {
  /**
   * Query if attribute by the given name is present
   *
   * @param attribName the name of the attribute that is being queried
   * @return true if data for this name is present, false otherwise
   */
  boolean hasData(String attribName);

  /**
   * Returns the data for the supplied attribute name as a float array, for
   * maximum flexibility
   *
   * @param attribName the (unique) name of the attribute
   * @return the attribute data as a float array
   * @throws IllegalArgumentException if no attribute by the given name is
   *                                  found
   */
  float[] getData(String attribName) throws IllegalArgumentException;

  /**
   * set the data for the given attribute. If attribute is not already present,
   * it will be added now. If data is already present for the attribute, it will
   * be overwritten
   *
   * @param attribName the name of the attribute to be added/set
   * @param data       the data as an array of floats for maximum flexibility
   * @throws IllegalArgumentException if an implementation does not support that
   *                                  attribute
   */
  void setData(String attribName, float[] data) throws IllegalArgumentException;

  /**
   * Get a list of all the attribute names supported by an implementation
   *
   * @return an array of String objects storing the name of all supported
   * attribute names
   */
  String[] getAllAttributes();

}


text:
import Scenario from './Scenario'
import Bugsnag from '@bugsnag/react-native'

export class UnhandledOverrideJsErrorScenario extends Scenario {
  constructor (configuration, jsConfig) {
    super()
    jsConfig.onError = (event) => {
      event.unhandled = false
    }
  }

  async run () {
    Bugsnag.startSession()
    await this.timeout(750)
    throw new Error('UnhandledOverrideJsErrorScenario')
  }
}


text:
function sov2mat
% multiple time series in strung-out-vector for to time series
% matrix
%
% D Meko 4-22-96
%
%
%************** INPUT -- SCREEN PROMPTED **********************
%
% The user will be prompted for file names for the following input:
%
% file1 -- .dat: V (mV x 1)r:  the strung-out vector
% file2 -- .dat: P (mP x 5)i: pointer matrix to years
%		and rows for each time series in V. Cols of P are
%		1-sequence no. 2,3-start,end year, 4,5-start,end row index
%
% file3 -- .txt: T(mT x nT)s, the name-tag
%		file from which series id or names can be drawn.
%		First 6 characters of these names are stored in string matrix
%		along with the time series matrix in the ouput .mat file
%		These names can also be used as column headings ifthe user
%		wants a BMDP-type output matrix
% file4 -- .dat: I (mI x 1)i row pointer to T indicating the subset
%		of series to be included in the output matrix
% file5 -- name of .mat file to hold the output time series
%		and its associated names of series
% file6 -- (optional) name of output .dat file to hold the BMDP-style
%		output matrix -- not yet built in
%
%  OTHER SCREEN-PROMPTED INPUT
%
% yrgo,yrsp -- desired start and end year of the output matrix
% xmiss -- filler code for missing values in the output matrix
%		Not yet built in; program now uses NaN
%
%************** OUTPUT **********************
%
% 1 -  .MAT  file holding matrices X and N.  X is the time-series
%		matrix for years yrgo to yrsp with data for the subset
%		of variables identified by I. First row of X is the year.
%		N is the string matrix of series names for X.
% 2 (optional) -  .DAT holding same information as the .MAT file,
%		but with the names as column headings
%
%****************** NOTES ***************************************
%
% Leading 8 chars of the lines in the name-tag file are used
% as the series identifiers.  If fewer than 8 characters
% (e.g.,   x01.crn), right-padded with blanks

%
file1=uigetfile('*.dat','strgout_ vector input data file');
file2=uigetfile('*.dat','rowyr_ pointer matrix for input sov');
file3=uigetfile('*.dat','crnfn_ chronology file names input file');
file4=uigetfile('*.dat','use_  series-to-use pointer file');

% Load the strung-out-vector file
eval(['load ',file1]);

% Extract the matrix name for the strung-out vector; store the
% strung-out vector as V
line=file1;
i1=find(line=='.');
vtemp=line(1:(i1-1));
eval(['V = ',vtemp,';'])
eval(['clear ',vtemp]);

% Load file with the years/rows pointer
eval(['load ',file2]);

% Extract the matrix name for the years pointer; store in P
line=file2;
i1=find(line=='.');
vtemp=line(1:(i1-1));
eval(['P = ',vtemp,';'])
eval(['clear ',vtemp]);

% Check P
[mP,nP]=size(P); % mP is the number of time series in the sov
if nP~=5,
	error('P should have 5 columns')
end

% Get the series name or id information off a .txt file.
% This file holds a string in each line.  The string identifies
% a time series in the sov.  The strings might differ in length
% from line to line, so cannot read in a matrix.
fid3=fopen(file3,'r+');
n1=0; % counter for number of lines in file3
while 1
	line = fgetl(fid3);
	if ~isstr(line), break, end
	n1=n1+1;
end

if n1~=mP,
	error('N of lines in file3 not equal to row-size of P')
end

fseek(fid3,0,-1); % rewind file3

% Build name-tag string matrix S.  Assume col-size 8
S='        ';
for n = 1:n1;
	line=fgetl(fid3);
	line=deblank(line);
	ns = length(line);
	if ns>8,
		line=line(1:8);
	end
	S=str2mat(S,line);
end
S(1,:)=[];
fclose(fid3)

% Load the file with the pointer to rows of P and S indicating
% which series to put in the output matrix
eval(['load ',file4]);

% Extract the matrix of the selection pointer; store in I
line=file4;
i1=find(line=='.');
vtemp=line(1:(i1-1));
eval(['K= ',vtemp,';'])
eval(['clear ',vtemp]);
[mK,nK]=size(K);

if nK~=1,
	error('File 4 should consist of single column')
end
if mK>mP
	error('Row-size of K too large')
end
if min(K)<1 | max(K)>mP,
	error('A value of K in file4 is too big')
end

% Cull the desired rows of S,P
N=S(K,:); % names of desired series
P=P(K,:);

% What time period do you want the output to cover?
igo=input('Start year of output matrix: ');
isp=input('End year of output matrix: ');
if isp<=igo,
	error('Stop year must be later than start year')
end
if igo>=max(P(:,3))| isp <= min(P(:,2)),
	error('isp,igo inconsistent with time coverage in P')
end
nyrs = isp-igo+1;

% Initialize a matrix to store the output tsm
a = NaN;
X=a(ones(nyrs,1),ones(mK+1,1));
yrX = (igo:isp)';
X(:,1)=yrX;

% Loop over the desired series, pulling out the rows (years)
% in the "igo to isp" period, if any, and putting in the correct
% rows of X .  Must allow for possibility that some selected
% series may have no non-missing data in the nyrs key period.
for n = 1:mK;
	yr1 = [P(n,2):P(n,3)]';
	nsize=P(n,3)-P(n,2)+1; % number of years of data for this series
	if (yr1(1)>isp | yr1(nsize)<igo); % No usable data
		% skip this series
	else
		v = V(P(n,4):P(n,5)); % cv if data in V for this series
		% Make two pointer logical vectors.  L1 is pointer to v
		% marking rows in the igo to isp target period. L2 is a
		% pointer to X marking the usable years from V for this
		% series
		L1 = yr1>=igo  & yr1<=isp; % pointer to desired rows of v
		L2 = yrX>=P(n,2) & yrX<=P(n,3); %
		% Put the data in the slots
		X(L2,n+1)=v(L1);
	end
end
%

% Save result in .mat file
file5=uiputfile('*.mat','Save tsm and names string matrix as: ');
eval(['save ',file5,' X N'])


text:
<?xml version="1.0" encoding="utf-8"?>
<resources name="ru" flag="ru" title="Russian">
	<string name="_bx_smtp"><![CDATA[SMTP Почтовик]]></string>
	<string name="_bx_smtp_tester"><![CDATA[SMTP Почтовик - Тест]]></string>
	<string name="_bx_smtp_recipient"><![CDATA[Получатель]]></string>
	<string name="_bx_smtp_subject"><![CDATA[Тема]]></string>
	<string name="_bx_smtp_body"><![CDATA[Тело]]></string>
	<string name="_bx_smtp_is_html"><![CDATA[HTML форматирование]]></string>
	<string name="_bx_smtp_send_ok"><![CDATA[Письмо удачно отправлено]]></string>
	<string name="_bx_smtp_send_fail"><![CDATA[Отправка письма не удалась]]></string>
	<string name="_bx_smtp_help"><![CDATA[Помощь]]></string>
	<string name="_bx_smtp_help_text"><![CDATA[
        SMTP-авторизация  - большинство SMTP-серверов требуют SMTP-авторизацию, и Вам скорее всего нужно её задействовать.

        Имя сервера SMTP - лучше всего посылать почту от SMTP-сервера, установленного там же, где и Ваш сайт, поэтому укажите здесь или имя сайта, или localhost.

        Пользователь SMTP / пароль SMTP - зарегистрированные имя пользователя и пароль для отправки почты. Лучше всего использовать отдельный адрес для этой цели, например no-reply@mysite.com.

        Имя отправителя сообщения - получатели увидят это имя рядом с электронным адресом отправителя, так что, скорее всего, следует указать здесь имя Вашего сайта.

        Прикреплять к отправляемому письму все файлы из папки kmailer/attach - Вы можете загрузить любые файлы в папку modules/boonex/smtpmailer/data/attach, и при включённой данной функции они будут прикреплены к любому письму, посылаемому Вашим сайтом.

        Требует ли Ваш SMTP-сервер безопасного подключения - Вы можете отключить эту опцию, если имя Вашего хоста - localhost, так как безопасное подключение необязательно в данном случае.

        Включить SMTP-почтовик - возможно совсем отключить SMTP-почтовик, например, если Ваш SMTP-сервер временно не работает.

        Переопределять эл. адрес отправителя по умолчанию - установите этот адрес таким же, как и адрес Пользователя SMTP во избежание проблем с попаданием Вашей почты в спам.

        Вы также можете узнать вышеназванные значения из своего локального клиента эл. почты, если собираетесь использовать тот же эл. адрес для посылки сообщений через свой сайт.

        Если почта всё ещё попадает в папку "Спам", проверьте следующее:

Установите значение для поля "Переопределять эл. адрес отправителя по умолчанию" таким же, как и эл. адрес для поля "Пользователь SMTP"

Удостоверьтесь, что эл. адрес в поле "Переопределять эл. адрес отправителя по умолчанию" существует и указан правильно

Измените шаблоны эл. почты по умолчанию. Возможно, что какие-то из них не проходят через спам-фильтры, так как используются по умолчанию на большом количестве сайтов

Попросите своих пользователей добавить эл. адрес Вашего сайта в список контактов их имейл-клиента. В этом случае Ваша почта всегда будет оседать в папке "Входящие"

Здесь Вы найдёте великолепный инструктаж по тому, как занести Ваш сервер в "белый список" большинства популярных сервисов эл. почты, включая Yahoo

]]></string>
    <string name="_bx_smtp_adm_stg_cpt_type"><![CDATA[SMTP Почтовик]]></string>
    <string name="_bx_smtp_adm_stg_cpt_category_general"><![CDATA[Общие]]></string>

    <string name="_bx_smtp_option_on"><![CDATA[Включить SMTP Почтовик]]></string>
    <string name="_bx_smtp_option_auth"><![CDATA[SMTP аутентификация (если SMTP сервер требует логин и пароль)]]></string>
    <string name="_bx_smtp_option_username"><![CDATA[SMTP логин (только если включена SMTP аутентификация)]]></string>
    <string name="_bx_smtp_option_password"><![CDATA[SMTP пароль (только если включена SMTP аутентификация)]]></string>
    <string name="_bx_smtp_option_host"><![CDATA[SMTP сервер или IP адрес]]></string>
    <string name="_bx_smtp_option_port"><![CDATA[SMTP сервер порт (25 - по умолчанию, 465 - для SSL, 587 - для TLS)]]></string>
    <string name="_bx_smtp_option_secure"><![CDATA[Использовать шифрованное соединение для SMTP сервера]]></string>
    <string name="_bx_smtp_option_allow_selfsigned"><![CDATA[Разрешить не-безопасные сертификаты]]></string>
    <string name="_bx_smtp_option_from_name"><![CDATA[Имя, от которого отправлять все письма]]></string>
    <string name="_bx_smtp_option_from_email"><![CDATA[E-mail адрес, от которого отправлять все письма]]></string>
</resources>


text:
package bjohnson.ResponseHandlers;

import bjohnson.Request;

public interface ResponseBuilderInterface {
    Response getResponse(Request request);
}


text:
//
//  PRHOnOffButtonCell.m
//  PRHOnOffButton
//
//  Created by Peter Hosey on 2010-01-10.
//  Copyright 2010 Peter Hosey. All rights reserved.
//
//  Extended by Dain Kaplan on 2012-01-31.
//  Copyright 2012 Dain Kaplan. All rights reserved.
//

#import "OnOffSwitchControlCell.h"

#include <Carbon/Carbon.h>

// NOTE(dk): New defines for changing appearance
#define USE_COLORED_GRADIENTS true
#define SHOW_ONOFF_LABELS true

#define ONE_THIRD  (1.0 / 3.0)
#define ONE_HALF   (1.0 / 2.0)
#define TWO_THIRDS (2.0 / 3.0)

#define THUMB_WIDTH_FRACTION 0.45f
#define THUMB_CORNER_RADIUS 2.5f
#define FRAME_CORNER_RADIUS 2.5f

#define THUMB_GRADIENT_MAX_Y_WHITE 1.0f
#define THUMB_GRADIENT_MIN_Y_WHITE 0.9f
#define BACKGROUND_GRADIENT_MAX_Y_WHITE 0.5f
#define BACKGROUND_GRADIENT_MIN_Y_WHITE TWO_THIRDS
#define BACKGROUND_SHADOW_GRADIENT_WHITE 0.0f
#define BACKGROUND_SHADOW_GRADIENT_MAX_Y_ALPHA 0.35f
#define BACKGROUND_SHADOW_GRADIENT_MIN_Y_ALPHA 0.0f
#define BACKGROUND_SHADOW_GRADIENT_HEIGHT 4.0f
#define BORDER_WHITE 0.125f

#define THUMB_SHADOW_WHITE 0.0f
#define THUMB_SHADOW_ALPHA 0.5f
#define THUMB_SHADOW_BLUR 3.0f

#define DISABLED_OVERLAY_GRAY  1.0f
#define DISABLED_OVERLAY_ALPHA TWO_THIRDS

#define DOWNWARD_ANGLE_IN_DEGREES_FOR_VIEW(view) ([view isFlipped] ? 90.0f : 270.0f)

struct PRHOOBCStuffYouWouldNeedToIncludeCarbonHeadersFor {
	EventTime clickTimeout;
	HISize clickMaxDistance;
};

@interface  OnOffSwitchControlCell()

@property (readwrite, retain) NSColor *customOnColor;
@property (readwrite, retain) NSColor *customOffColor;

- (CGFloat)centerXForThumbWithFrame:(NSRect)cellFrame;
- (void)drawText:(NSString *)text withFrame:(NSRect)textFrame;
- (void)tintBackgroundWithFrame:(NSRect)cellFrame inView:(NSView *)controlView;
@end

// NOTE(dk): start additions

// NOTE(dk): Mostly taken from: http://cocoaheads.org/peg-narrative/basic-drawing.html
NSRect DKCenterRect(NSRect smallRect, NSRect bigRect)
{
    NSRect centerRect;
    centerRect.size = smallRect.size;
    centerRect.origin.x = bigRect.origin.x + (bigRect.size.width - smallRect.size.width) / 2.0;
    centerRect.origin.y = bigRect.origin.y + (bigRect.size.height - smallRect.size.height) / 2.0;
    return (centerRect);
}
// NOTE(dk): end additions

@implementation OnOffSwitchControlCell

@synthesize showsOnOffLabels;
@synthesize onOffSwitchControlColors;
@synthesize customOffColor;
@synthesize customOnColor;
@synthesize onSwitchLabel;
@synthesize offSwitchLabel;

+ (BOOL) prefersTrackingUntilMouseUp {
	return /*YES, YES, a thousand times*/ YES;
}

+ (NSFocusRingType) defaultFocusRingType {
	return NSFocusRingTypeExterior;
}

- (void) furtherInit {
	[self setFocusRingType:[[self class] defaultFocusRingType]];
	stuff = NSZoneMalloc([self zone], sizeof(struct PRHOOBCStuffYouWouldNeedToIncludeCarbonHeadersFor));
	OSStatus err = HIMouseTrackingGetParameters(kMouseParamsSticky, &(stuff->clickTimeout), &(stuff->clickMaxDistance));
	if (err != noErr) {
		//Values returned by the above function call as of 10.6.3.
		stuff->clickTimeout = ONE_THIRD * kEventDurationSecond;
		stuff->clickMaxDistance = (HISize){ 6.0f, 6.0f };
	}
	// NOTE(dk): start additions
	self.showsOnOffLabels = YES;
	self.onOffSwitchControlColors = OnOffSwitchControlBlueGreyColors;
	self.onSwitchLabel = @"ON";
	self.offSwitchLabel = @"OFF";
	// NOTE(dk): end additions
}

- (id) initImageCell:(NSImage *)image {
	if ((self = [super initImageCell:image])) {
		[self furtherInit];
	}
	return self;
}
- (id) initTextCell:(NSString *)str {
	if ((self = [super initTextCell:str])) {
		[self furtherInit];
	}
	return self;
}
//HAX: IB (I guess?) sets our focus ring type to None for some reason. Nobody asks defaultFocusRingType unless we do it (in furtherInit).
- (id) initWithCoder:(NSCoder *)decoder {
	if ((self = [super initWithCoder:decoder])) {
		[self furtherInit];
	}
	return self;
}

- (NSRect) thumbRectInFrame:(NSRect)cellFrame {
	cellFrame.size.width -= 2.0f;
	cellFrame.size.height -= 2.0f;
	cellFrame.origin.x += 1.0f;
	cellFrame.origin.y += 1.0f;

	NSRect thumbFrame = cellFrame;
	thumbFrame.size.width *= THUMB_WIDTH_FRACTION;

	NSCellStateValue state = [self state];
	switch (state) {
		case NSOffState:
			//Far left. We're already there; don't do anything.
			break;
		case NSOnState:
			//Far right.
			thumbFrame.origin.x += (cellFrame.size.width - thumbFrame.size.width);
			break;
		case NSMixedState:
			//Middle.
			thumbFrame.origin.x = (cellFrame.size.width / 2.0f) - (thumbFrame.size.width / 2.0f);
			break;
	}

	return thumbFrame;
}

// NOTE(dk): start additions

- (void) setOnOffSwitchCustomOnColor:(NSColor *)onColor offColor:(NSColor *)offColor
{
	self.customOffColor = offColor;
	self.customOnColor = onColor;
}

// NOTE(dk): Split this out so we can call it elsewhere.
- (CGFloat)centerXForThumbWithFrame:(NSRect)cellFrame
{
	NSRect thumbFrame = [self thumbRectInFrame:cellFrame];
	if (tracking) {
		thumbFrame.origin.x += trackingPoint.x - initialTrackingPoint.x;

		//Clamp.
		CGFloat minOrigin = cellFrame.origin.x + 1;
		CGFloat maxOrigin = cellFrame.origin.x + (cellFrame.size.width - thumbFrame.size.width - 1);
		if (thumbFrame.origin.x < minOrigin)
			thumbFrame.origin.x = minOrigin;
		else if (thumbFrame.origin.x > maxOrigin)
			thumbFrame.origin.x = maxOrigin;
	}
	return NSMidX(thumbFrame);
}

// NOTE(dk): Center the text (as able) in the provided frame and draw it.
- (void)drawText:(NSString *)text withFrame:(NSRect)textFrame {
	CGFloat fontSize = [NSFont systemFontSizeForControlSize:[self controlSize]];
	//[NSFont fontWithName: @"HelveticaNeue-Bold" size:fontSize];
	NSFont *sysFont = [NSFont boldSystemFontOfSize:fontSize];
	NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
								sysFont, NSFontAttributeName,
								[NSColor whiteColor], NSForegroundColorAttributeName, nil];
	NSSize textSize = [text sizeWithAttributes:attributes];
	NSRect textBounds = DKCenterRect(NSMakeRect(0, 0, textSize.width, textSize.height), textFrame);
	[text drawInRect: textBounds withAttributes:attributes];
}

// Applies tints to the background to show the on/off state.
- (void)tintBackgroundWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {

	NSGraphicsContext *context = [NSGraphicsContext currentContext];
	[context saveGraphicsState];
	[[NSBezierPath bezierPathWithRoundedRect:cellFrame xRadius:FRAME_CORNER_RADIUS yRadius:FRAME_CORNER_RADIUS] addClip];

	// NOTE(dk): Make everything to the left of the thumb one color, and to the right another.
	NSRect thumbFrame = [self thumbRectInFrame:cellFrame];
	CGFloat thumbCenterX = [self centerXForThumbWithFrame:cellFrame];
	NSRect leftFrame;
	NSRect rightFrame;
	CGFloat offsetWidth = thumbCenterX;
	NSDivideRect(cellFrame, &leftFrame, &rightFrame, offsetWidth - cellFrame.origin.x, NSMinXEdge);
	//NSLog(@"OffsetWidth is: %f / %f; left: %f; right: %f", offsetWidth, cellFrame.origin.x, leftFrame.size.width, rightFrame.size.width);

	NSColor *onStartColor;
	NSColor *onEndColor;
	NSColor *offStartColor;
	NSColor *offEndColor;

	NSColor *_blueColor = [NSColor colorWithCalibratedRed:0.0 green:0.3 blue:1.0 alpha:0.6f];
	NSColor *_greyColor = [NSColor colorWithCalibratedRed:1.0 green:0.0 blue:0.0 alpha:0.0f];
	NSColor *_greenColor = [NSColor colorWithCalibratedRed:0.0 green:0.7 blue:0.0 alpha:0.6f];
	NSColor *_redColor = [NSColor colorWithCalibratedRed:0.7 green:0.0 blue:0.0 alpha:0.6f];

	switch (self.onOffSwitchControlColors) {
		case OnOffSwitchControlBlueGreyColors:
			onStartColor = onEndColor = _blueColor;
			offStartColor = offEndColor = _greyColor;
			break;
		case OnOffSwitchControlGreenRedColors:
			onStartColor = onEndColor = _greenColor;
			offStartColor = offEndColor = _redColor;
			break;
		case OnOffSwitchControlBlueRedColors:
			onStartColor = onEndColor = _blueColor;
			offStartColor = offEndColor = _redColor;
			break;
		case OnOffSwitchControlCustomColors:
			onStartColor = onEndColor = self.customOnColor;
			offStartColor = offEndColor = self.customOffColor;
			break;
		case OnOffSwitchControlDefaultColors:
		default:
			onStartColor = onEndColor = nil;
			offStartColor = offEndColor = nil;
	}

	if (onStartColor != nil && offStartColor != nil) {
		NSGradient *leftBackground = [[NSGradient alloc] initWithStartingColor:onStartColor
																	endingColor:onEndColor];
		NSGradient *rightBackground = [[NSGradient alloc] initWithStartingColor:offStartColor
																	 endingColor:offEndColor];
		[leftBackground drawInRect:NSInsetRect(leftFrame, 1.0f, 1.0f) angle:DOWNWARD_ANGLE_IN_DEGREES_FOR_VIEW(controlView)];
		[rightBackground drawInRect:NSInsetRect(rightFrame, 1.0f, 1.0f) angle:DOWNWARD_ANGLE_IN_DEGREES_FOR_VIEW(controlView)];
		[leftBackground release];
		[rightBackground release];
	}
	[context restoreGraphicsState];

	if (self.showsOnOffLabels) {
		// Left label
		NSRect leftSizeFrame;
		leftSizeFrame.origin.x = (tracking ? thumbCenterX-(thumbFrame.size.width/2) : thumbFrame.origin.x) - (cellFrame.size.width - thumbFrame.size.width) + 2;
		leftSizeFrame.origin.y = cellFrame.origin.y;
		leftSizeFrame.size.width = cellFrame.size.width - thumbFrame.size.width - 2;
		leftSizeFrame.size.height = cellFrame.size.height;
		[self drawText:self.onSwitchLabel withFrame:leftSizeFrame];

		// Right label
		NSRect rightSizeFrame = leftSizeFrame;
		rightSizeFrame.origin.x = (tracking ? thumbCenterX+(thumbFrame.size.width/2): thumbFrame.origin.x + thumbFrame.size.width) + 1;
		rightSizeFrame.origin.y = cellFrame.origin.y;
		[self drawText:self.offSwitchLabel withFrame:rightSizeFrame];
	}
}
// NOTE(dk): end additions

- (void) drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
	if (tracking)
		trackingCellFrame = cellFrame;

	NSGraphicsContext *context = [NSGraphicsContext currentContext];
	CGContextRef quartzContext = [context graphicsPort];
	CGContextBeginTransparencyLayer(quartzContext, /*auxInfo*/ NULL);

	//Draw the background, then the frame.
	NSBezierPath *borderPath = [NSBezierPath bezierPathWithRoundedRect:NSInsetRect(cellFrame, 1.0f, 1.0f) xRadius:FRAME_CORNER_RADIUS yRadius:FRAME_CORNER_RADIUS];

	[[NSColor colorWithCalibratedWhite:BORDER_WHITE alpha:1.0f] setStroke];
	[borderPath stroke];

	NSColor *startColor = [NSColor colorWithCalibratedWhite:BACKGROUND_GRADIENT_MAX_Y_WHITE alpha:1.0f];
	NSColor *endColor = [NSColor colorWithCalibratedWhite:BACKGROUND_GRADIENT_MIN_Y_WHITE alpha:1.0f];
	NSGradient *background = [[[NSGradient alloc] initWithStartingColor:startColor endingColor:endColor] autorelease];
	[background drawInBezierPath:borderPath angle:DOWNWARD_ANGLE_IN_DEGREES_FOR_VIEW(controlView)];

	[context saveGraphicsState];

	[[NSBezierPath bezierPathWithRoundedRect:cellFrame xRadius:FRAME_CORNER_RADIUS yRadius:FRAME_CORNER_RADIUS] addClip];

	// NOTE(dk): start additions
	if (USE_COLORED_GRADIENTS && ![self allowsMixedState]) {
		[self tintBackgroundWithFrame:cellFrame inView:controlView];
	}
	// NOTE(dk): end additions

	NSGradient *backgroundShadow = [[[NSGradient alloc] initWithStartingColor:[NSColor colorWithCalibratedWhite:BACKGROUND_SHADOW_GRADIENT_WHITE alpha:BACKGROUND_SHADOW_GRADIENT_MAX_Y_ALPHA] endingColor:[NSColor colorWithCalibratedWhite:BACKGROUND_SHADOW_GRADIENT_WHITE alpha:BACKGROUND_SHADOW_GRADIENT_MIN_Y_ALPHA]] autorelease];
	NSRect backgroundShadowRect = cellFrame;
	if (![controlView isFlipped])
		backgroundShadowRect.origin.y += backgroundShadowRect.size.height - BACKGROUND_SHADOW_GRADIENT_HEIGHT;
	backgroundShadowRect.size.height = BACKGROUND_SHADOW_GRADIENT_HEIGHT;
	[backgroundShadow drawInRect:backgroundShadowRect angle:DOWNWARD_ANGLE_IN_DEGREES_FOR_VIEW(controlView)];

	[context restoreGraphicsState];

	[self drawInteriorWithFrame:cellFrame inView:controlView];

	if (![self isEnabled]) {
		CGColorRef color = CGColorCreateGenericGray(DISABLED_OVERLAY_GRAY, DISABLED_OVERLAY_ALPHA);
		if (color) {
			CGContextSetBlendMode(quartzContext, kCGBlendModeLighten);
			CGContextSetFillColorWithColor(quartzContext, color);
			CGContextFillRect(quartzContext, NSRectToCGRect(cellFrame));

			CFRelease(color);
		}
	}
	CGContextEndTransparencyLayer(quartzContext);
}

- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
	//Draw the thumb.
	NSRect thumbFrame = [self thumbRectInFrame:cellFrame];

	NSGraphicsContext *context = [NSGraphicsContext currentContext];
	[context saveGraphicsState];

	cellFrame.size.width -= 2.0f;
	cellFrame.size.height -= 2.0f;
	cellFrame.origin.x += 1.0f;
	cellFrame.origin.y += 1.0f;
	NSBezierPath *clipPath = [NSBezierPath bezierPathWithRoundedRect:cellFrame xRadius:THUMB_CORNER_RADIUS yRadius:THUMB_CORNER_RADIUS];
	[clipPath addClip];

	if (tracking) {
		thumbFrame.origin.x += trackingPoint.x - initialTrackingPoint.x;

		//Clamp.
		CGFloat minOrigin = cellFrame.origin.x;
		CGFloat maxOrigin = cellFrame.origin.x + (cellFrame.size.width - thumbFrame.size.width);
		if (thumbFrame.origin.x < minOrigin)
			thumbFrame.origin.x = minOrigin;
		else if (thumbFrame.origin.x > maxOrigin)
			thumbFrame.origin.x = maxOrigin;

		trackingThumbCenterX = [self centerXForThumbWithFrame:cellFrame];
	}

	NSBezierPath *thumbPath = [NSBezierPath bezierPathWithRoundedRect:thumbFrame xRadius:THUMB_CORNER_RADIUS yRadius:THUMB_CORNER_RADIUS];
	NSShadow *thumbShadow = [[[NSShadow alloc] init] autorelease];
	[thumbShadow setShadowColor:[NSColor colorWithCalibratedWhite:THUMB_SHADOW_WHITE alpha:THUMB_SHADOW_ALPHA]];
	[thumbShadow setShadowBlurRadius:THUMB_SHADOW_BLUR];
	[thumbShadow setShadowOffset:NSZeroSize];
	[thumbShadow set];
	[[NSColor whiteColor] setFill];
	if ([self showsFirstResponder] && ([self focusRingType] != NSFocusRingTypeNone))
		NSSetFocusRingStyle(NSFocusRingBelow);
	[thumbPath fill];
	NSGradient *thumbGradient = [[[NSGradient alloc] initWithStartingColor:[NSColor colorWithCalibratedWhite:THUMB_GRADIENT_MAX_Y_WHITE alpha:1.0f] endingColor:[NSColor colorWithCalibratedWhite:THUMB_GRADIENT_MIN_Y_WHITE alpha:1.0f]] autorelease];
	[thumbGradient drawInBezierPath:thumbPath angle:DOWNWARD_ANGLE_IN_DEGREES_FOR_VIEW(controlView)];

	[context restoreGraphicsState];

	if (tracking && (getenv("PRHOnOffButtonCellDebug") != NULL)) {
		NSBezierPath *thumbCenterLine = [NSBezierPath bezierPath];
		[thumbCenterLine moveToPoint:(NSPoint){ NSMidX(thumbFrame), thumbFrame.origin.y +thumbFrame.size.height * ONE_THIRD }];
		[thumbCenterLine lineToPoint:(NSPoint){ NSMidX(thumbFrame), thumbFrame.origin.y +thumbFrame.size.height * TWO_THIRDS }];
		[thumbCenterLine stroke];

		NSBezierPath *sectionLines = [NSBezierPath bezierPath];
		if ([self allowsMixedState]) {
			[sectionLines moveToPoint:(NSPoint){ cellFrame.origin.x + cellFrame.size.width * ONE_THIRD, NSMinY(cellFrame) }];
			[sectionLines lineToPoint:(NSPoint){ cellFrame.origin.x + cellFrame.size.width * ONE_THIRD, NSMaxY(cellFrame) }];
			[sectionLines moveToPoint:(NSPoint){ cellFrame.origin.x + cellFrame.size.width * TWO_THIRDS, NSMinY(cellFrame) }];
			[sectionLines lineToPoint:(NSPoint){ cellFrame.origin.x + cellFrame.size.width * TWO_THIRDS, NSMaxY(cellFrame) }];
		} else {
			[sectionLines moveToPoint:(NSPoint){ cellFrame.origin.x + cellFrame.size.width * ONE_HALF, NSMinY(cellFrame) }];
			[sectionLines lineToPoint:(NSPoint){ cellFrame.origin.x + cellFrame.size.width * ONE_HALF, NSMaxY(cellFrame) }];
		}
		[sectionLines stroke];
	}
}

- (NSUInteger)hitTestForEvent:(NSEvent *)event inRect:(NSRect)cellFrame ofView:(NSView *)controlView {
	NSPoint mouseLocation = [controlView convertPoint:[event locationInWindow] fromView:nil];
	return NSPointInRect(mouseLocation, cellFrame) ? (NSCellHitContentArea | NSCellHitTrackableArea) : NSCellHitNone;
}

- (BOOL) startTrackingAt:(NSPoint)startPoint inView:(NSView *)controlView {
	//We rely on NSControl behavior, so only start tracking if this is a control.
	tracking = YES;
	trackingPoint = initialTrackingPoint = startPoint;
	trackingTime = initialTrackingTime = [NSDate timeIntervalSinceReferenceDate];
	return [controlView isKindOfClass:[NSControl class]];
}
- (BOOL) continueTracking:(NSPoint)lastPoint at:(NSPoint)currentPoint inView:(NSView *)controlView {
	NSControl *control = [controlView isKindOfClass:[NSControl class]] ? (NSControl *)controlView : nil;
	if (control) {
		trackingPoint = currentPoint;
		//No need to update the time here as long as nothing cares about it.
		trackingTime = initialTrackingTime = [NSDate timeIntervalSinceReferenceDate];
		[control drawCell:self];
		return YES;
	}
	tracking = NO;
	return NO;
}
- (void)stopTracking:(NSPoint)lastPoint at:(NSPoint)stopPoint inView:(NSView *)controlView mouseIsUp:(BOOL)flag {
	tracking = NO;
	trackingTime = [NSDate timeIntervalSinceReferenceDate];

	NSControl *control = [controlView isKindOfClass:[NSControl class]] ? (NSControl *)controlView : nil;
	if (control) {
		CGFloat xFraction = trackingThumbCenterX / trackingCellFrame.size.width;

		BOOL isClickNotDragByTime = (trackingTime - initialTrackingTime) < stuff->clickTimeout;
		BOOL isClickNotDragBySpaceX = (stopPoint.x - initialTrackingPoint.x) < stuff->clickMaxDistance.width;
		BOOL isClickNotDragBySpaceY = (stopPoint.y - initialTrackingPoint.y) < stuff->clickMaxDistance.height;
		BOOL isClickNotDrag = isClickNotDragByTime && isClickNotDragBySpaceX && isClickNotDragBySpaceY;

		if (!isClickNotDrag) {
			NSCellStateValue desiredState;

			if ([self allowsMixedState]) {
				if (xFraction < ONE_THIRD)
					desiredState = NSOffState;
				else if (xFraction >= TWO_THIRDS)
					desiredState = NSOnState;
				else
					desiredState = NSMixedState;
			} else {
				if (xFraction < ONE_HALF)
					desiredState = NSOffState;
				else
					desiredState = NSOnState;
			}

			//We actually need to set the state to the one *before* the one we want, because NSCell will advance it. I'm not sure how to thwart that without breaking -setNextState, which breaks AXPress and the space bar.
			NSCellStateValue stateBeforeDesiredState;
			switch (desiredState) {
				case NSOnState:
					if ([self allowsMixedState]) {
						stateBeforeDesiredState = NSMixedState;
						break;
					}
					//Fall through.
				case NSMixedState:
					stateBeforeDesiredState = NSOffState;
					break;
				case NSOffState:
					stateBeforeDesiredState = NSOnState;
					break;
			}

			[self setState:stateBeforeDesiredState];
		}
	}
}

@end


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import platform
import sys
from datetime import datetime
from xml.dom import minidom

import py

import pytest
from _pytest.junitxml import LogXML
from _pytest.reports import BaseReport

def runandparse(testdir, *args):
    resultpath = testdir.tmpdir.join("junit.xml")
    result = testdir.runpytest("--junitxml=%s" % resultpath, *args)
    xmldoc = minidom.parse(str(resultpath))
    return result, DomNode(xmldoc)

def assert_attr(node, **kwargs):
    __tracebackhide__ = True

    def nodeval(node, name):
        anode = node.getAttributeNode(name)
        if anode is not None:
            return anode.value

    expected = {name: str(value) for name, value in kwargs.items()}
    on_node = {name: nodeval(node, name) for name in expected}
    assert on_node == expected

class DomNode(object):
    def __init__(self, dom):
        self.__node = dom

    def __repr__(self):
        return self.__node.toxml()

    def find_first_by_tag(self, tag):
        return self.find_nth_by_tag(tag, 0)

    def _by_tag(self, tag):
        return self.__node.getElementsByTagName(tag)

    @property
    def children(self):
        return [type(self)(x) for x in self.__node.childNodes]

    @property
    def get_unique_child(self):
        children = self.children
        assert len(children) == 1
        return children[0]

    def find_nth_by_tag(self, tag, n):
        items = self._by_tag(tag)
        try:
            nth = items[n]
        except IndexError:
            pass
        else:
            return type(self)(nth)

    def find_by_tag(self, tag):
        t = type(self)
        return [t(x) for x in self.__node.getElementsByTagName(tag)]

    def __getitem__(self, key):
        node = self.__node.getAttributeNode(key)
        if node is not None:
            return node.value

    def assert_attr(self, **kwargs):
        __tracebackhide__ = True
        return assert_attr(self.__node, **kwargs)

    def toxml(self):
        return self.__node.toxml()

    @property
    def text(self):
        return self.__node.childNodes[0].wholeText

    @property
    def tag(self):
        return self.__node.tagName

    @property
    def next_sibling(self):
        return type(self)(self.__node.nextSibling)

class TestPython(object):
    def test_summing_simple(self, testdir):
        testdir.makepyfile(
            """
            import pytest
            def test_pass():
                pass
            def test_fail():
                assert 0
            def test_skip():
                pytest.skip("")
            @pytest.mark.xfail
            def test_xfail():
                assert 0
            @pytest.mark.xfail
            def test_xpass():
                assert 1
        """
        )
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(name="pytest", errors=0, failures=1, skipped=2, tests=5)

    def test_summing_simple_with_errors(self, testdir):
        testdir.makepyfile(
            """
            import pytest
            @pytest.fixture
            def fixture():
                raise Exception()
            def test_pass():
                pass
            def test_fail():
                assert 0
            def test_error(fixture):
                pass
            @pytest.mark.xfail
            def test_xfail():
                assert False
            @pytest.mark.xfail(strict=True)
            def test_xpass():
                assert True
        """
        )
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(name="pytest", errors=1, failures=2, skipped=1, tests=5)

    def test_hostname_in_xml(self, testdir):
        testdir.makepyfile(
            """
            def test_pass():
                pass
        """
        )
        result, dom = runandparse(testdir)
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(hostname=platform.node())

    def test_timestamp_in_xml(self, testdir):
        testdir.makepyfile(
            """
            def test_pass():
                pass
        """
        )
        start_time = datetime.now()
        result, dom = runandparse(testdir)
        node = dom.find_first_by_tag("testsuite")
        timestamp = datetime.strptime(node["timestamp"], "%Y-%m-%dT%H:%M:%S.%f")
        assert start_time <= timestamp < datetime.now()

    def test_timing_function(self, testdir):
        testdir.makepyfile(
            """
            import time, pytest
            def setup_module():
                time.sleep(0.01)
            def teardown_module():
                time.sleep(0.01)
            def test_sleep():
                time.sleep(0.01)
        """
        )
        result, dom = runandparse(testdir)
        node = dom.find_first_by_tag("testsuite")
        tnode = node.find_first_by_tag("testcase")
        val = tnode["time"]
        assert round(float(val), 2) >= 0.03

    @pytest.mark.parametrize("duration_report", ["call", "total"])
    def test_junit_duration_report(self, testdir, monkeypatch, duration_report):

        # mock LogXML.node_reporter so it always sets a known duration to each test report object
        original_node_reporter = LogXML.node_reporter

        def node_reporter_wrapper(s, report):
            report.duration = 1.0
            reporter = original_node_reporter(s, report)
            return reporter

        monkeypatch.setattr(LogXML, "node_reporter", node_reporter_wrapper)

        testdir.makepyfile(
            """
            def test_foo():
                pass
        """
        )
        result, dom = runandparse(
            testdir, "-o", "junit_duration_report={}".format(duration_report)
        )
        node = dom.find_first_by_tag("testsuite")
        tnode = node.find_first_by_tag("testcase")
        val = float(tnode["time"])
        if duration_report == "total":
            assert val == 3.0
        else:
            assert duration_report == "call"
            assert val == 1.0

    def test_setup_error(self, testdir):
        testdir.makepyfile(
            """
            import pytest

            @pytest.fixture
            def arg(request):
                raise ValueError()
            def test_function(arg):
                pass
        """
        )
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(errors=1, tests=1)
        tnode = node.find_first_by_tag("testcase")
        tnode.assert_attr(classname="test_setup_error", name="test_function")
        fnode = tnode.find_first_by_tag("error")
        fnode.assert_attr(message="test setup failure")
        assert "ValueError" in fnode.toxml()

    def test_teardown_error(self, testdir):
        testdir.makepyfile(
            """
            import pytest

            @pytest.fixture
            def arg():
                yield
                raise ValueError()
            def test_function(arg):
                pass
        """
        )
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.find_first_by_tag("testsuite")
        tnode = node.find_first_by_tag("testcase")
        tnode.assert_attr(classname="test_teardown_error", name="test_function")
        fnode = tnode.find_first_by_tag("error")
        fnode.assert_attr(message="test teardown failure")
        assert "ValueError" in fnode.toxml()

    def test_call_failure_teardown_error(self, testdir):
        testdir.makepyfile(
            """
            import pytest

            @pytest.fixture
            def arg():
                yield
                raise Exception("Teardown Exception")
            def test_function(arg):
                raise Exception("Call Exception")
        """
        )
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(errors=1, failures=1, tests=1)
        first, second = dom.find_by_tag("testcase")
        if not first or not second or first == second:
            assert 0
        fnode = first.find_first_by_tag("failure")
        fnode.assert_attr(message="Exception: Call Exception")
        snode = second.find_first_by_tag("error")
        snode.assert_attr(message="test teardown failure")

    def test_skip_contains_name_reason(self, testdir):
        testdir.makepyfile(
            """
            import pytest
            def test_skip():
                pytest.skip("hello23")
        """
        )
        result, dom = runandparse(testdir)
        assert result.ret == 0
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(skipped=1)
        tnode = node.find_first_by_tag("testcase")
        tnode.assert_attr(classname="test_skip_contains_name_reason", name="test_skip")
        snode = tnode.find_first_by_tag("skipped")
        snode.assert_attr(type="pytest.skip", message="hello23")

    def test_mark_skip_contains_name_reason(self, testdir):
        testdir.makepyfile(
            """
            import pytest
            @pytest.mark.skip(reason="hello24")
            def test_skip():
                assert True
        """
        )
        result, dom = runandparse(testdir)
        assert result.ret == 0
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(skipped=1)
        tnode = node.find_first_by_tag("testcase")
        tnode.assert_attr(
            classname="test_mark_skip_contains_name_reason", name="test_skip"
        )
        snode = tnode.find_first_by_tag("skipped")
        snode.assert_attr(type="pytest.skip", message="hello24")

    def test_mark_skipif_contains_name_reason(self, testdir):
        testdir.makepyfile(
            """
            import pytest
            GLOBAL_CONDITION = True
            @pytest.mark.skipif(GLOBAL_CONDITION, reason="hello25")
            def test_skip():
                assert True
        """
        )
        result, dom = runandparse(testdir)
        assert result.ret == 0
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(skipped=1)
        tnode = node.find_first_by_tag("testcase")
        tnode.assert_attr(
            classname="test_mark_skipif_contains_name_reason", name="test_skip"
        )
        snode = tnode.find_first_by_tag("skipped")
        snode.assert_attr(type="pytest.skip", message="hello25")

    def test_mark_skip_doesnt_capture_output(self, testdir):
        testdir.makepyfile(
            """
            import pytest
            @pytest.mark.skip(reason="foo")
            def test_skip():
                print("bar!")
        """
        )
        result, dom = runandparse(testdir)
        assert result.ret == 0
        node_xml = dom.find_first_by_tag("testsuite").toxml()
        assert "bar!" not in node_xml

    def test_classname_instance(self, testdir):
        testdir.makepyfile(
            """
            class TestClass(object):
                def test_method(self):
                    assert 0
        """
        )
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(failures=1)
        tnode = node.find_first_by_tag("testcase")
        tnode.assert_attr(
            classname="test_classname_instance.TestClass", name="test_method"
        )

    def test_classname_nested_dir(self, testdir):
        p = testdir.tmpdir.ensure("sub", "test_hello.py")
        p.write("def test_func(): 0/0")
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(failures=1)
        tnode = node.find_first_by_tag("testcase")
        tnode.assert_attr(classname="sub.test_hello", name="test_func")

    def test_internal_error(self, testdir):
        testdir.makeconftest("def pytest_runtest_protocol(): 0 / 0")
        testdir.makepyfile("def test_function(): pass")
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(errors=1, tests=1)
        tnode = node.find_first_by_tag("testcase")
        tnode.assert_attr(classname="pytest", name="internal")
        fnode = tnode.find_first_by_tag("error")
        fnode.assert_attr(message="internal error")
        assert "Division" in fnode.toxml()

    @pytest.mark.parametrize("junit_logging", ["no", "system-out", "system-err"])
    def test_failure_function(self, testdir, junit_logging):
        testdir.makepyfile(
            """
            import logging
            import sys

            def test_fail():
                print("hello-stdout")
                sys.stderr.write("hello-stderr\\n")
                logging.info('info msg')
                logging.warning('warning msg')
                raise ValueError(42)
        """
        )

        result, dom = runandparse(testdir, "-o", "junit_logging=%s" % junit_logging)
        assert result.ret
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(failures=1, tests=1)
        tnode = node.find_first_by_tag("testcase")
        tnode.assert_attr(classname="test_failure_function", name="test_fail")
        fnode = tnode.find_first_by_tag("failure")
        fnode.assert_attr(message="ValueError: 42")
        assert "ValueError" in fnode.toxml()
        systemout = fnode.next_sibling
        assert systemout.tag == "system-out"
        assert "hello-stdout" in systemout.toxml()
        assert "info msg" not in systemout.toxml()
        systemerr = systemout.next_sibling
        assert systemerr.tag == "system-err"
        assert "hello-stderr" in systemerr.toxml()
        assert "info msg" not in systemerr.toxml()

        if junit_logging == "system-out":
            assert "warning msg" in systemout.toxml()
            assert "warning msg" not in systemerr.toxml()
        elif junit_logging == "system-err":
            assert "warning msg" not in systemout.toxml()
            assert "warning msg" in systemerr.toxml()
        elif junit_logging == "no":
            assert "warning msg" not in systemout.toxml()
            assert "warning msg" not in systemerr.toxml()

    def test_failure_verbose_message(self, testdir):
        testdir.makepyfile(
            """
            import sys
            def test_fail():
                assert 0, "An error"
        """
        )

        result, dom = runandparse(testdir)
        node = dom.find_first_by_tag("testsuite")
        tnode = node.find_first_by_tag("testcase")
        fnode = tnode.find_first_by_tag("failure")
        fnode.assert_attr(message="AssertionError: An error assert 0")

    def test_failure_escape(self, testdir):
        testdir.makepyfile(
            """
            import pytest
            @pytest.mark.parametrize('arg1', "<&'", ids="<&'")
            def test_func(arg1):
                print(arg1)
                assert 0
        """
        )
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(failures=3, tests=3)

        for index, char in enumerate("<&'"):

            tnode = node.find_nth_by_tag("testcase", index)
            tnode.assert_attr(
                classname="test_failure_escape", name="test_func[%s]" % char
            )
            sysout = tnode.find_first_by_tag("system-out")
            text = sysout.text
            assert text == "%s\n" % char

    def test_junit_prefixing(self, testdir):
        testdir.makepyfile(
            """
            def test_func():
                assert 0
            class TestHello(object):
                def test_hello(self):
                    pass
        """
        )
        result, dom = runandparse(testdir, "--junitprefix=xyz")
        assert result.ret
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(failures=1, tests=2)
        tnode = node.find_first_by_tag("testcase")
        tnode.assert_attr(classname="xyz.test_junit_prefixing", name="test_func")
        tnode = node.find_nth_by_tag("testcase", 1)
        tnode.assert_attr(
            classname="xyz.test_junit_prefixing.TestHello", name="test_hello"
        )

    def test_xfailure_function(self, testdir):
        testdir.makepyfile(
            """
            import pytest
            def test_xfail():
                pytest.xfail("42")
        """
        )
        result, dom = runandparse(testdir)
        assert not result.ret
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(skipped=1, tests=1)
        tnode = node.find_first_by_tag("testcase")
        tnode.assert_attr(classname="test_xfailure_function", name="test_xfail")
        fnode = tnode.find_first_by_tag("skipped")
        fnode.assert_attr(type="pytest.xfail", message="42")
        # assert "ValueError" in fnode.toxml()

    def test_xfailure_marker(self, testdir):
        testdir.makepyfile(
            """
            import pytest
            @pytest.mark.xfail(reason="42")
            def test_xfail():
                assert False
        """
        )
        result, dom = runandparse(testdir)
        assert not result.ret
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(skipped=1, tests=1)
        tnode = node.find_first_by_tag("testcase")
        tnode.assert_attr(classname="test_xfailure_marker", name="test_xfail")
        fnode = tnode.find_first_by_tag("skipped")
        fnode.assert_attr(type="pytest.xfail", message="42")

    def test_xfail_captures_output_once(self, testdir):
        testdir.makepyfile(
            """
            import sys
            import pytest

            @pytest.mark.xfail()
            def test_fail():
                sys.stdout.write('XFAIL This is stdout')
                sys.stderr.write('XFAIL This is stderr')
                assert 0
        """
        )
        result, dom = runandparse(testdir)
        node = dom.find_first_by_tag("testsuite")
        tnode = node.find_first_by_tag("testcase")
        assert len(tnode.find_by_tag("system-err")) == 1
        assert len(tnode.find_by_tag("system-out")) == 1

    def test_xfailure_xpass(self, testdir):
        testdir.makepyfile(
            """
            import pytest
            @pytest.mark.xfail
            def test_xpass():
                pass
        """
        )
        result, dom = runandparse(testdir)
        # assert result.ret
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(skipped=0, tests=1)
        tnode = node.find_first_by_tag("testcase")
        tnode.assert_attr(classname="test_xfailure_xpass", name="test_xpass")

    def test_xfailure_xpass_strict(self, testdir):
        testdir.makepyfile(
            """
            import pytest
            @pytest.mark.xfail(strict=True, reason="This needs to fail!")
            def test_xpass():
                pass
        """
        )
        result, dom = runandparse(testdir)
        # assert result.ret
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(skipped=0, tests=1)
        tnode = node.find_first_by_tag("testcase")
        tnode.assert_attr(classname="test_xfailure_xpass_strict", name="test_xpass")
        fnode = tnode.find_first_by_tag("failure")
        fnode.assert_attr(message="[XPASS(strict)] This needs to fail!")

    def test_collect_error(self, testdir):
        testdir.makepyfile("syntax error")
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(errors=1, tests=1)
        tnode = node.find_first_by_tag("testcase")
        fnode = tnode.find_first_by_tag("error")
        fnode.assert_attr(message="collection failure")
        assert "SyntaxError" in fnode.toxml()

    def test_unicode(self, testdir):
        value = "hx\xc4\x85\xc4\x87\n"
        testdir.makepyfile(
            """
            # coding: latin1
            def test_hello():
                print(%r)
                assert 0
        """
            % value
        )
        result, dom = runandparse(testdir)
        assert result.ret == 1
        tnode = dom.find_first_by_tag("testcase")
        fnode = tnode.find_first_by_tag("failure")
        if not sys.platform.startswith("java"):
            assert "hx" in fnode.toxml()

    def test_assertion_binchars(self, testdir):
        """this test did fail when the escaping wasnt strict"""
        testdir.makepyfile(
            """

            M1 = '\x01\x02\x03\x04'
            M2 = '\x01\x02\x03\x05'

            def test_str_compare():
                assert M1 == M2
            """
        )
        result, dom = runandparse(testdir)
        print(dom.toxml())

    def test_pass_captures_stdout(self, testdir):
        testdir.makepyfile(
            """
            def test_pass():
                print('hello-stdout')
        """
        )
        result, dom = runandparse(testdir)
        node = dom.find_first_by_tag("testsuite")
        pnode = node.find_first_by_tag("testcase")
        systemout = pnode.find_first_by_tag("system-out")
        assert "hello-stdout" in systemout.toxml()

    def test_pass_captures_stderr(self, testdir):
        testdir.makepyfile(
            """
            import sys
            def test_pass():
                sys.stderr.write('hello-stderr')
        """
        )
        result, dom = runandparse(testdir)
        node = dom.find_first_by_tag("testsuite")
        pnode = node.find_first_by_tag("testcase")
        systemout = pnode.find_first_by_tag("system-err")
        assert "hello-stderr" in systemout.toxml()

    def test_setup_error_captures_stdout(self, testdir):
        testdir.makepyfile(
            """
            import pytest

            @pytest.fixture
            def arg(request):
                print('hello-stdout')
                raise ValueError()
            def test_function(arg):
                pass
        """
        )
        result, dom = runandparse(testdir)
        node = dom.find_first_by_tag("testsuite")
        pnode = node.find_first_by_tag("testcase")
        systemout = pnode.find_first_by_tag("system-out")
        assert "hello-stdout" in systemout.toxml()

    def test_setup_error_captures_stderr(self, testdir):
        testdir.makepyfile(
            """
            import sys
            import pytest

            @pytest.fixture
            def arg(request):
                sys.stderr.write('hello-stderr')
                raise ValueError()
            def test_function(arg):
                pass
        """
        )
        result, dom = runandparse(testdir)
        node = dom.find_first_by_tag("testsuite")
        pnode = node.find_first_by_tag("testcase")
        systemout = pnode.find_first_by_tag("system-err")
        assert "hello-stderr" in systemout.toxml()

    def test_avoid_double_stdout(self, testdir):
        testdir.makepyfile(
            """
            import sys
            import pytest

            @pytest.fixture
            def arg(request):
                yield
                sys.stdout.write('hello-stdout teardown')
                raise ValueError()
            def test_function(arg):
                sys.stdout.write('hello-stdout call')
        """
        )
        result, dom = runandparse(testdir)
        node = dom.find_first_by_tag("testsuite")
        pnode = node.find_first_by_tag("testcase")
        systemout = pnode.find_first_by_tag("system-out")
        assert "hello-stdout call" in systemout.toxml()
        assert "hello-stdout teardown" in systemout.toxml()

def test_mangle_test_address():
    from _pytest.junitxml import mangle_test_address

    address = "::".join(["a/my.py.thing.py", "Class", "()", "method", "[a-1-::]"])
    newnames = mangle_test_address(address)
    assert newnames == ["a.my.py.thing", "Class", "method", "[a-1-::]"]

def test_dont_configure_on_slaves(tmpdir):
    gotten = []

    class FakeConfig(object):
        def __init__(self):
            self.pluginmanager = self
            self.option = self

        def getini(self, name):
            return "pytest"

        junitprefix = None
        # XXX: shouldnt need tmpdir ?
        xmlpath = str(tmpdir.join("junix.xml"))
        register = gotten.append

    fake_config = FakeConfig()
    from _pytest import junitxml

    junitxml.pytest_configure(fake_config)
    assert len(gotten) == 1
    FakeConfig.slaveinput = None
    junitxml.pytest_configure(fake_config)
    assert len(gotten) == 1

class TestNonPython(object):
    def test_summing_simple(self, testdir):
        testdir.makeconftest(
            """
            import pytest
            def pytest_collect_file(path, parent):
                if path.ext == ".xyz":
                    return MyItem(path, parent)
            class MyItem(pytest.Item):
                def __init__(self, path, parent):
                    super(MyItem, self).__init__(path.basename, parent)
                    self.fspath = path
                def runtest(self):
                    raise ValueError(42)
                def repr_failure(self, excinfo):
                    return "custom item runtest failed"
        """
        )
        testdir.tmpdir.join("myfile.xyz").write("hello")
        result, dom = runandparse(testdir)
        assert result.ret
        node = dom.find_first_by_tag("testsuite")
        node.assert_attr(errors=0, failures=1, skipped=0, tests=1)
        tnode = node.find_first_by_tag("testcase")
        tnode.assert_attr(name="myfile.xyz")
        fnode = tnode.find_first_by_tag("failure")
        fnode.assert_attr(message="custom item runtest failed")
        assert "custom item runtest failed" in fnode.toxml()

def test_nullbyte(testdir):
    # A null byte can not occur in XML (see section 2.2 of the spec)
    testdir.makepyfile(
        """
        import sys
        def test_print_nullbyte():
            sys.stdout.write('Here the null -->' + chr(0) + '<--')
            sys.stdout.write('In repr form -->' + repr(chr(0)) + '<--')
            assert False
    """
    )
    xmlf = testdir.tmpdir.join("junit.xml")
    testdir.runpytest("--junitxml=%s" % xmlf)
    text = xmlf.read()
    assert "\x00" not in text
    assert "#x00" in text

def test_nullbyte_replace(testdir):
    # Check if the null byte gets replaced
    testdir.makepyfile(
        """
        import sys
        def test_print_nullbyte():
            sys.stdout.write('Here the null -->' + chr(0) + '<--')
            sys.stdout.write('In repr form -->' + repr(chr(0)) + '<--')
            assert False
    """
    )
    xmlf = testdir.tmpdir.join("junit.xml")
    testdir.runpytest("--junitxml=%s" % xmlf)
    text = xmlf.read()
    assert "#x0" in text

def test_invalid_xml_escape():
    # Test some more invalid xml chars, the full range should be
    # tested really but let's just thest the edges of the ranges
    # intead.
    # XXX This only tests low unicode character points for now as
    #     there are some issues with the testing infrastructure for
    #     the higher ones.
    # XXX Testing 0xD (\r) is tricky as it overwrites the just written
    #     line in the output, so we skip it too.
    global unichr
    try:
        unichr(65)
    except NameError:
        unichr = chr
    invalid = (
        0x00,
        0x1,
        0xB,
        0xC,
        0xE,
        0x19,
        27,  # issue #126
        0xD800,
        0xDFFF,
        0xFFFE,
        0x0FFFF,
    )  # , 0x110000)
    valid = (0x9, 0xA, 0x20)
    # 0xD, 0xD7FF, 0xE000, 0xFFFD, 0x10000, 0x10FFFF)

    from _pytest.junitxml import bin_xml_escape

    for i in invalid:
        got = bin_xml_escape(unichr(i)).uniobj
        if i <= 0xFF:
            expected = "#x%02X" % i
        else:
            expected = "#x%04X" % i
        assert got == expected
    for i in valid:
        assert chr(i) == bin_xml_escape(unichr(i)).uniobj

def test_logxml_path_expansion(tmpdir, monkeypatch):
    home_tilde = py.path.local(os.path.expanduser("~")).join("test.xml")
    xml_tilde = LogXML("~%stest.xml" % tmpdir.sep, None)
    assert xml_tilde.logfile == home_tilde

    monkeypatch.setenv("HOME", str(tmpdir))
    home_var = os.path.normpath(os.path.expandvars("$HOME/test.xml"))
    xml_var = LogXML("$HOME%stest.xml" % tmpdir.sep, None)
    assert xml_var.logfile == home_var

def test_logxml_changingdir(testdir):
    testdir.makepyfile(
        """
        def test_func():
            import os
            os.chdir("a")
    """
    )
    testdir.tmpdir.mkdir("a")
    result = testdir.runpytest("--junitxml=a/x.xml")
    assert result.ret == 0
    assert testdir.tmpdir.join("a/x.xml").check()

def test_logxml_makedir(testdir):
    """--junitxml should automatically create directories for the xml file"""
    testdir.makepyfile(
        """
        def test_pass():
            pass
    """
    )
    result = testdir.runpytest("--junitxml=path/to/results.xml")
    assert result.ret == 0
    assert testdir.tmpdir.join("path/to/results.xml").check()

def test_logxml_check_isdir(testdir):
    """Give an error if --junit-xml is a directory (#2089)"""
    result = testdir.runpytest("--junit-xml=.")
    result.stderr.fnmatch_lines(["*--junitxml must be a filename*"])

def test_escaped_parametrized_names_xml(testdir):
    testdir.makepyfile(
        """
        import pytest
        @pytest.mark.parametrize('char', [u"\\x00"])
        def test_func(char):
            assert char
    """
    )
    result, dom = runandparse(testdir)
    assert result.ret == 0
    node = dom.find_first_by_tag("testcase")
    node.assert_attr(name="test_func[\\x00]")

def test_double_colon_split_function_issue469(testdir):
    testdir.makepyfile(
        """
        import pytest
        @pytest.mark.parametrize('param', ["double::colon"])
        def test_func(param):
            pass
    """
    )
    result, dom = runandparse(testdir)
    assert result.ret == 0
    node = dom.find_first_by_tag("testcase")
    node.assert_attr(classname="test_double_colon_split_function_issue469")
    node.assert_attr(name="test_func[double::colon]")

def test_double_colon_split_method_issue469(testdir):
    testdir.makepyfile(
        """
        import pytest
        class TestClass(object):
            @pytest.mark.parametrize('param', ["double::colon"])
            def test_func(self, param):
                pass
    """
    )
    result, dom = runandparse(testdir)
    assert result.ret == 0
    node = dom.find_first_by_tag("testcase")
    node.assert_attr(classname="test_double_colon_split_method_issue469.TestClass")
    node.assert_attr(name="test_func[double::colon]")

def test_unicode_issue368(testdir):
    path = testdir.tmpdir.join("test.xml")
    log = LogXML(str(path), None)
    ustr = u"ВНИ!"

    class Report(BaseReport):
        longrepr = ustr
        sections = []
        nodeid = "something"
        location = "tests/filename.py", 42, "TestClass.method"

    test_report = Report()

    # hopefully this is not too brittle ...
    log.pytest_sessionstart()
    node_reporter = log._opentestcase(test_report)
    node_reporter.append_failure(test_report)
    node_reporter.append_collect_error(test_report)
    node_reporter.append_collect_skipped(test_report)
    node_reporter.append_error(test_report)
    test_report.longrepr = "filename", 1, ustr
    node_reporter.append_skipped(test_report)
    test_report.longrepr = "filename", 1, "Skipped: 卡嘣嘣"
    node_reporter.append_skipped(test_report)
    test_report.wasxfail = ustr
    node_reporter.append_skipped(test_report)
    log.pytest_sessionfinish()

def test_record_property(testdir):
    testdir.makepyfile(
        """
        import pytest

        @pytest.fixture
        def other(record_property):
            record_property("bar", 1)
        def test_record(record_property, other):
            record_property("foo", "<1");
    """
    )
    result, dom = runandparse(testdir, "-rwv")
    node = dom.find_first_by_tag("testsuite")
    tnode = node.find_first_by_tag("testcase")
    psnode = tnode.find_first_by_tag("properties")
    pnodes = psnode.find_by_tag("property")
    pnodes[0].assert_attr(name="bar", value="1")
    pnodes[1].assert_attr(name="foo", value="<1")

def test_record_property_same_name(testdir):
    testdir.makepyfile(
        """
        def test_record_with_same_name(record_property):
            record_property("foo", "bar")
            record_property("foo", "baz")
    """
    )
    result, dom = runandparse(testdir, "-rw")
    node = dom.find_first_by_tag("testsuite")
    tnode = node.find_first_by_tag("testcase")
    psnode = tnode.find_first_by_tag("properties")
    pnodes = psnode.find_by_tag("property")
    pnodes[0].assert_attr(name="foo", value="bar")
    pnodes[1].assert_attr(name="foo", value="baz")

@pytest.mark.parametrize("fixture_name", ["record_property", "record_xml_attribute"])
def test_record_fixtures_without_junitxml(testdir, fixture_name):
    testdir.makepyfile(
        """
        def test_record({fixture_name}):
            {fixture_name}("foo", "bar")
    """.format(
            fixture_name=fixture_name
        )
    )
    result = testdir.runpytest()
    assert result.ret == 0

@pytest.mark.filterwarnings("default")
def test_record_attribute(testdir):
    testdir.makeini(
        """
        [pytest]
        junit_family = xunit1
    """
    )
    testdir.makepyfile(
        """
        import pytest

        @pytest.fixture
        def other(record_xml_attribute):
            record_xml_attribute("bar", 1)
        def test_record(record_xml_attribute, other):
            record_xml_attribute("foo", "<1");
    """
    )
    result, dom = runandparse(testdir, "-rw")
    node = dom.find_first_by_tag("testsuite")
    tnode = node.find_first_by_tag("testcase")
    tnode.assert_attr(bar="1")
    tnode.assert_attr(foo="<1")
    result.stdout.fnmatch_lines(
        ["*test_record_attribute.py:6:*record_xml_attribute is an experimental feature"]
    )

@pytest.mark.filterwarnings("default")
@pytest.mark.parametrize("fixture_name", ["record_xml_attribute", "record_property"])
def test_record_fixtures_xunit2(testdir, fixture_name):
    """Ensure record_xml_attribute and record_property drop values when outside of legacy family
    """
    testdir.makeini(
        """
        [pytest]
        junit_family = xunit2
    """
    )
    testdir.makepyfile(
        """
        import pytest

        @pytest.fixture
        def other({fixture_name}):
            {fixture_name}("bar", 1)
        def test_record({fixture_name}, other):
            {fixture_name}("foo", "<1");
    """.format(
            fixture_name=fixture_name
        )
    )

    result, dom = runandparse(testdir, "-rw")
    expected_lines = []
    if fixture_name == "record_xml_attribute":
        expected_lines.append(
            "*test_record_fixtures_xunit2.py:6:*record_xml_attribute is an experimental feature"
        )
    expected_lines = [
        "*test_record_fixtures_xunit2.py:6:*{fixture_name} is incompatible "
        "with junit_family 'xunit2' (use 'legacy' or 'xunit1')".format(
            fixture_name=fixture_name
        )
    ]
    result.stdout.fnmatch_lines(expected_lines)

def test_random_report_log_xdist(testdir, monkeypatch):
    """xdist calls pytest_runtest_logreport as they are executed by the slaves,
    with nodes from several nodes overlapping, so junitxml must cope with that
    to produce correct reports. #1064
    """
    pytest.importorskip("xdist")
    monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", raising=False)
    testdir.makepyfile(
        """
        import pytest, time
        @pytest.mark.parametrize('i', list(range(30)))
        def test_x(i):
            assert i != 22
    """
    )
    _, dom = runandparse(testdir, "-n2")
    suite_node = dom.find_first_by_tag("testsuite")
    failed = []
    for case_node in suite_node.find_by_tag("testcase"):
        if case_node.find_first_by_tag("failure"):
            failed.append(case_node["name"])

    assert failed == ["test_x[22]"]

def test_root_testsuites_tag(testdir):
    testdir.makepyfile(
        """
        def test_x():
            pass
    """
    )
    _, dom = runandparse(testdir)
    root = dom.get_unique_child
    assert root.tag == "testsuites"
    suite_node = root.get_unique_child
    assert suite_node.tag == "testsuite"

def test_runs_twice(testdir):
    f = testdir.makepyfile(
        """
        def test_pass():
            pass
    """
    )

    result, dom = runandparse(testdir, f, f)
    assert "INTERNALERROR" not in result.stdout.str()
    first, second = [x["classname"] for x in dom.find_by_tag("testcase")]
    assert first == second

@pytest.mark.xfail(reason="hangs", run=False)
def test_runs_twice_xdist(testdir):
    pytest.importorskip("xdist")
    f = testdir.makepyfile(
        """
        def test_pass():
            pass
    """
    )

    result, dom = runandparse(testdir, f, "--dist", "each", "--tx", "2*popen")
    assert "INTERNALERROR" not in result.stdout.str()
    first, second = [x["classname"] for x in dom.find_by_tag("testcase")]
    assert first == second

def test_fancy_items_regression(testdir):
    # issue 1259
    testdir.makeconftest(
        """
        import pytest
        class FunItem(pytest.Item):
            def runtest(self):
                pass
        class NoFunItem(pytest.Item):
            def runtest(self):
                pass

        class FunCollector(pytest.File):
            def collect(self):
                return [
                    FunItem('a', self),
                    NoFunItem('a', self),
                    NoFunItem('b', self),
                ]

        def pytest_collect_file(path, parent):
            if path.check(ext='.py'):
                return FunCollector(path, parent)
    """
    )

    testdir.makepyfile(
        """
        def test_pass():
            pass
    """
    )

    result, dom = runandparse(testdir)

    assert "INTERNALERROR" not in result.stdout.str()

    items = sorted("%(classname)s %(name)s" % x for x in dom.find_by_tag("testcase"))
    import pprint

    pprint.pprint(items)
    assert items == [
        u"conftest a",
        u"conftest a",
        u"conftest b",
        u"test_fancy_items_regression a",
        u"test_fancy_items_regression a",
        u"test_fancy_items_regression b",
        u"test_fancy_items_regression test_pass",
    ]

def test_global_properties(testdir):
    path = testdir.tmpdir.join("test_global_properties.xml")
    log = LogXML(str(path), None)

    class Report(BaseReport):
        sections = []
        nodeid = "test_node_id"

    log.pytest_sessionstart()
    log.add_global_property("foo", 1)
    log.add_global_property("bar", 2)
    log.pytest_sessionfinish()

    dom = minidom.parse(str(path))

    properties = dom.getElementsByTagName("properties")

    assert properties.length == 1, "There must be one <properties> node"

    property_list = dom.getElementsByTagName("property")

    assert property_list.length == 2, "There most be only 2 property nodes"

    expected = {"foo": "1", "bar": "2"}
    actual = {}

    for p in property_list:
        k = str(p.getAttribute("name"))
        v = str(p.getAttribute("value"))
        actual[k] = v

    assert actual == expected

def test_url_property(testdir):
    test_url = "http://www.github.com/pytest-dev"
    path = testdir.tmpdir.join("test_url_property.xml")
    log = LogXML(str(path), None)

    class Report(BaseReport):
        longrepr = "FooBarBaz"
        sections = []
        nodeid = "something"
        location = "tests/filename.py", 42, "TestClass.method"
        url = test_url

    test_report = Report()

    log.pytest_sessionstart()
    node_reporter = log._opentestcase(test_report)
    node_reporter.append_failure(test_report)
    log.pytest_sessionfinish()

    test_case = minidom.parse(str(path)).getElementsByTagName("testcase")[0]

    assert (
        test_case.getAttribute("url") == test_url
    ), "The URL did not get written to the xml"

def test_record_testsuite_property(testdir):
    testdir.makepyfile(
        """
        def test_func1(record_testsuite_property):
            record_testsuite_property("stats", "all good")

        def test_func2(record_testsuite_property):
            record_testsuite_property("stats", 10)
    """
    )
    result, dom = runandparse(testdir)
    assert result.ret == 0
    node = dom.find_first_by_tag("testsuite")
    properties_node = node.find_first_by_tag("properties")
    p1_node = properties_node.find_nth_by_tag("property", 0)
    p2_node = properties_node.find_nth_by_tag("property", 1)
    p1_node.assert_attr(name="stats", value="all good")
    p2_node.assert_attr(name="stats", value="10")

def test_record_testsuite_property_junit_disabled(testdir):
    testdir.makepyfile(
        """
        def test_func1(record_testsuite_property):
            record_testsuite_property("stats", "all good")
    """
    )
    result = testdir.runpytest()
    assert result.ret == 0

@pytest.mark.parametrize("junit", [True, False])
def test_record_testsuite_property_type_checking(testdir, junit):
    testdir.makepyfile(
        """
        def test_func1(record_testsuite_property):
            record_testsuite_property(1, 2)
    """
    )
    args = ("--junitxml=tests.xml",) if junit else ()
    result = testdir.runpytest(*args)
    assert result.ret == 1
    result.stdout.fnmatch_lines(
        ["*TypeError: name parameter needs to be a string, but int given"]
    )

@pytest.mark.parametrize("suite_name", ["my_suite", ""])
def test_set_suite_name(testdir, suite_name):
    if suite_name:
        testdir.makeini(
            """
            [pytest]
            junit_suite_name={}
        """.format(
                suite_name
            )
        )
        expected = suite_name
    else:
        expected = "pytest"
    testdir.makepyfile(
        """
        import pytest

        def test_func():
            pass
    """
    )
    result, dom = runandparse(testdir)
    assert result.ret == 0
    node = dom.find_first_by_tag("testsuite")
    node.assert_attr(name=expected)

def test_escaped_skipreason_issue3533(testdir):
    testdir.makepyfile(
        """
        import pytest
        @pytest.mark.skip(reason='1 <> 2')
        def test_skip():
            pass
    """
    )
    _, dom = runandparse(testdir)
    node = dom.find_first_by_tag("testcase")
    snode = node.find_first_by_tag("skipped")
    assert "1 <> 2" in snode.text
    snode.assert_attr(message="1 <> 2")

def test_logging_passing_tests_disabled_does_not_log_test_output(testdir):
    testdir.makeini(
        """
        [pytest]
        junit_log_passing_tests=False
        junit_logging=system-out
    """
    )
    testdir.makepyfile(
        """
        import pytest
        import logging
        import sys

        def test_func():
            sys.stdout.write('This is stdout')
            sys.stderr.write('This is stderr')
            logging.warning('hello')
    """
    )
    result, dom = runandparse(testdir)
    assert result.ret == 0
    node = dom.find_first_by_tag("testcase")
    assert len(node.find_by_tag("system-err")) == 0
    assert len(node.find_by_tag("system-out")) == 0

@pytest.mark.parametrize("junit_logging", ["no", "system-out", "system-err"])
def test_logging_passing_tests_disabled_logs_output_for_failing_test_issue5430(
    testdir, junit_logging
):
    testdir.makeini(
        """
        [pytest]
        junit_log_passing_tests=False
    """
    )
    testdir.makepyfile(
        """
        import pytest
        import logging
        import sys

        def test_func():
            logging.warning('hello')
            assert 0
    """
    )
    result, dom = runandparse(testdir, "-o", "junit_logging=%s" % junit_logging)
    assert result.ret == 1
    node = dom.find_first_by_tag("testcase")
    if junit_logging == "system-out":
        assert len(node.find_by_tag("system-err")) == 0
        assert len(node.find_by_tag("system-out")) == 1
    elif junit_logging == "system-err":
        assert len(node.find_by_tag("system-err")) == 1
        assert len(node.find_by_tag("system-out")) == 0
    else:
        assert junit_logging == "no"
        assert len(node.find_by_tag("system-err")) == 0
        assert len(node.find_by_tag("system-out")) == 0


text:
namespace ash {
namespace nearby {

class MockNearbySharingDecoder : public sharing::mojom::NearbySharingDecoder {
 public:
  MockNearbySharingDecoder();
  explicit MockNearbySharingDecoder(const MockNearbySharingDecoder&) = delete;
  MockNearbySharingDecoder& operator=(const MockNearbySharingDecoder&) = delete;
  ~MockNearbySharingDecoder() override;

  const mojo::SharedRemote<sharing::mojom::NearbySharingDecoder>&
  shared_remote() const {
    return shared_remote_;
  }

  void BindInterface(mojo::PendingReceiver<sharing::mojom::NearbySharingDecoder>
                         pending_receiver);

  // sharing::mojom::NearbySharingDecoder:
  MOCK_METHOD(void,
              DecodeAdvertisement,
              (const std::vector<uint8_t>& data,
               DecodeAdvertisementCallback callback),
              (override));
  MOCK_METHOD(void,
              DecodeFrame,
              (const std::vector<uint8_t>& data, DecodeFrameCallback callback),
              (override));

 private:
  mojo::ReceiverSet<sharing::mojom::NearbySharingDecoder> receiver_set_;
  mojo::SharedRemote<sharing::mojom::NearbySharingDecoder> shared_remote_;
};

}  // namespace nearby
}  // namespace ash

#endif  // ASH_SERVICES_NEARBY_PUBLIC_CPP_MOCK_NEARBY_SHARING_DECODER_H_