repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/ByeRequestBuilder.java | sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/request/ByeRequestBuilder.java | package io.github.lunasaw.sip.common.transmit.request;
import javax.sip.header.ContactHeader;
import javax.sip.header.UserAgentHeader;
import javax.sip.message.Request;
import io.github.lunasaw.sip.common.entity.FromDevice;
import io.github.lunasaw.sip.common.entity.SipMessage;
import io.github.lunasaw.sip.common.entity.ToDevice;
import io.github.lunasaw.sip.common.utils.SipRequestUtils;
/**
* BYE请求构建器
*
* @author luna
*/
public class ByeRequestBuilder extends AbstractSipRequestBuilder {
/**
* 创建BYE请求
*
* @param fromDevice 发送设备
* @param toDevice 接收设备
* @param callId 呼叫ID
* @return BYE请求
*/
public Request buildByeRequest(FromDevice fromDevice, ToDevice toDevice, String callId) {
SipMessage sipMessage = SipMessage.getByeBody();
sipMessage.setMethod(Request.BYE);
sipMessage.setCallId(callId);
return build(fromDevice, toDevice, sipMessage);
}
@Override
protected void customizeRequest(Request request, FromDevice fromDevice, ToDevice toDevice, SipMessage sipMessage) {
// 添加User-Agent头部
UserAgentHeader userAgentHeader = SipRequestUtils.createUserAgentHeader(fromDevice.getAgent());
request.addHeader(userAgentHeader);
// 添加Contact头部
ContactHeader contactHeader = SipRequestUtils.createContactHeader(fromDevice.getUserId(), fromDevice.getHostAddress());
request.addHeader(contactHeader);
}
} | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/AbstractSipRequestStrategy.java | sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/AbstractSipRequestStrategy.java | package io.github.lunasaw.sip.common.transmit.strategy;
import io.github.lunasaw.sip.common.entity.FromDevice;
import io.github.lunasaw.sip.common.entity.ToDevice;
import io.github.lunasaw.sip.common.subscribe.SubscribeInfo;
import io.github.lunasaw.sip.common.transmit.SipMessageTransmitter;
import io.github.lunasaw.sip.common.transmit.event.Event;
import io.github.lunasaw.sip.common.utils.SipRequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.sip.message.Request;
/**
* 抽象的基础SIP请求策略类
* 提供通用的请求发送逻辑,子类只需要实现具体的请求构建逻辑
*
* @author lin
*/
@Slf4j
public abstract class AbstractSipRequestStrategy implements SipRequestStrategy {
@Override
public String sendRequest(FromDevice fromDevice, ToDevice toDevice, String content, Event errorEvent, Event okEvent) {
// 生成一个唯一的呼叫ID
return sendRequest(fromDevice, toDevice, content, SipRequestUtils.getNewCallId(), errorEvent, okEvent);
}
@Override
public String sendRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId, Event errorEvent, Event okEvent) {
if (StringUtils.isBlank(callId)) {
callId = SipRequestUtils.getNewCallId();
}
Request request = buildRequest(fromDevice, toDevice, content, callId);
SipMessageTransmitter.transmitMessage(fromDevice.getIp(), request, errorEvent, okEvent);
return callId;
}
@Override
public String sendRequestWithSubscribe(FromDevice fromDevice, ToDevice toDevice, String content, SubscribeInfo subscribeInfo, String callId, Event errorEvent, Event okEvent) {
Request request = buildRequestWithSubscribe(fromDevice, toDevice, content, subscribeInfo, callId);
SipMessageTransmitter.transmitMessage(fromDevice.getIp(), request, errorEvent, okEvent);
return callId;
}
@Override
public String sendRequestWithSubject(FromDevice fromDevice, ToDevice toDevice, String content, String subject, String callId, Event errorEvent,
Event okEvent) {
Request request = buildRequestWithSubject(fromDevice, toDevice, content, subject, callId);
SipMessageTransmitter.transmitMessage(fromDevice.getIp(), request, errorEvent, okEvent);
return callId;
}
/**
* 构建基础请求
*
* @param fromDevice 发送方设备
* @param toDevice 接收方设备
* @param content 请求内容
* @param callId 呼叫ID
* @return 构建的请求
*/
protected abstract Request buildRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId);
/**
* 构建带主题的请求
*
* @param fromDevice 发送方设备
* @param toDevice 接收方设备
* @param content 请求内容
* @param subject 主题
* @param callId 呼叫ID
* @return 构建的请求
*/
protected Request buildRequestWithSubject(FromDevice fromDevice, ToDevice toDevice, String content, String subject, String callId) {
return buildRequest(fromDevice, toDevice, content, callId);
}
/**
* 构建带订阅信息的请求
*
* @param fromDevice 发送方设备
* @param toDevice 接收方设备
* @param content 请求内容
* @param subscribeInfo 订阅信息
* @param callId 呼叫ID
* @return 构建的请求
*/
protected Request buildRequestWithSubscribe(FromDevice fromDevice, ToDevice toDevice, String content, SubscribeInfo subscribeInfo, String callId) {
return buildRequest(fromDevice, toDevice, content, callId);
}
} | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/SipRequestStrategy.java | sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/SipRequestStrategy.java | package io.github.lunasaw.sip.common.transmit.strategy;
import io.github.lunasaw.sip.common.entity.FromDevice;
import io.github.lunasaw.sip.common.entity.ToDevice;
import io.github.lunasaw.sip.common.subscribe.SubscribeInfo;
import io.github.lunasaw.sip.common.transmit.event.Event;
/**
* SIP请求发送策略接口
* 定义通用的请求发送模式,支持不同的请求类型
*
* @author lin
*/
public interface SipRequestStrategy {
/**
* 发送请求
*
* @param fromDevice 发送方设备
* @param toDevice 接收方设备
* @param content 请求内容
* @param errorEvent 错误事件处理器
* @param okEvent 成功事件处理器
* @return 呼叫ID
*/
String sendRequest(FromDevice fromDevice, ToDevice toDevice, String content, Event errorEvent, Event okEvent);
/**
* 发送请求
*
* @param fromDevice 发送方设备
* @param toDevice 接收方设备
* @param content 请求内容
* @param callId 呼叫ID
* @param errorEvent 错误事件处理器
* @param okEvent 成功事件处理器
* @return 呼叫ID
*/
String sendRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId, Event errorEvent, Event okEvent);
/**
* 发送带订阅信息的请求
*
* @param fromDevice 发送方设备
* @param toDevice 接收方设备
* @param content 请求内容
* @param subscribeInfo 订阅信息
* @param callId 呼叫ID
* @param errorEvent 错误事件处理器
* @param okEvent 成功事件处理器
* @return 呼叫ID
*/
String sendRequestWithSubscribe(FromDevice fromDevice, ToDevice toDevice, String content, SubscribeInfo subscribeInfo, String callId, Event errorEvent, Event okEvent);
/**
* 发送带主题的请求
*
* @param fromDevice 发送方设备
* @param toDevice 接收方设备
* @param content 请求内容
* @param subject 主题
* @param callId 呼叫ID
* @param errorEvent 错误事件处理器
* @param okEvent 成功事件处理器
* @return 呼叫ID
*/
default String sendRequestWithSubject(FromDevice fromDevice, ToDevice toDevice, String content, String subject, String callId, Event errorEvent,
Event okEvent) {
return sendRequest(fromDevice, toDevice, content, callId, errorEvent, okEvent);
}
} | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/SipRequestStrategyFactory.java | sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/SipRequestStrategyFactory.java | package io.github.lunasaw.sip.common.transmit.strategy;
import io.github.lunasaw.sip.common.transmit.strategy.impl.*;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* SIP请求策略工厂
* 管理和获取不同的请求策略
*
* @author lin
*/
@Slf4j
public class SipRequestStrategyFactory {
private static final Map<String, SipRequestStrategy> STRATEGY_MAP = new ConcurrentHashMap<>();
static {
// 初始化默认策略
STRATEGY_MAP.put("MESSAGE", new MessageRequestStrategy());
STRATEGY_MAP.put("INVITE", new InviteRequestStrategy());
STRATEGY_MAP.put("SUBSCRIBE", new SubscribeRequestStrategy());
STRATEGY_MAP.put("NOTIFY", new NotifyRequestStrategy());
STRATEGY_MAP.put("BYE", new ByeRequestStrategy());
STRATEGY_MAP.put("ACK", new AckRequestStrategy());
STRATEGY_MAP.put("INFO", new InfoRequestStrategy());
}
/**
* 获取请求策略
*
* @param method SIP方法名
* @return 请求策略
*/
public static SipRequestStrategy getStrategy(String method) {
return STRATEGY_MAP.get(method.toUpperCase());
}
/**
* 获取注册请求策略
*
* @param expires 过期时间
* @return 注册请求策略
*/
public static SipRequestStrategy getRegisterStrategy(Integer expires) {
return new RegisterRequestStrategy(expires);
}
/**
* 注册自定义策略
*
* @param method SIP方法名
* @param strategy 策略实现
*/
public static void registerStrategy(String method, SipRequestStrategy strategy) {
STRATEGY_MAP.put(method.toUpperCase(), strategy);
log.info("注册SIP请求策略: {} -> {}", method, strategy.getClass().getSimpleName());
}
/**
* 移除策略
*
* @param method SIP方法名
*/
public static void removeStrategy(String method) {
STRATEGY_MAP.remove(method.toUpperCase());
log.info("移除SIP请求策略: {}", method);
}
} | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/impl/MessageRequestStrategy.java | sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/impl/MessageRequestStrategy.java | package io.github.lunasaw.sip.common.transmit.strategy.impl;
import io.github.lunasaw.sip.common.entity.FromDevice;
import io.github.lunasaw.sip.common.entity.ToDevice;
import io.github.lunasaw.sip.common.subscribe.SubscribeInfo;
import io.github.lunasaw.sip.common.transmit.request.SipRequestBuilderFactory;
import io.github.lunasaw.sip.common.transmit.strategy.AbstractSipRequestStrategy;
import lombok.extern.slf4j.Slf4j;
import javax.sip.message.Request;
/**
* MESSAGE请求策略实现
*
* @author lin
*/
@Slf4j
public class MessageRequestStrategy extends AbstractSipRequestStrategy {
@Override
protected Request buildRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) {
return SipRequestBuilderFactory.createMessageRequest(fromDevice, toDevice, content, callId);
}
} | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/impl/AckRequestStrategy.java | sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/impl/AckRequestStrategy.java | package io.github.lunasaw.sip.common.transmit.strategy.impl;
import io.github.lunasaw.sip.common.entity.FromDevice;
import io.github.lunasaw.sip.common.entity.ToDevice;
import io.github.lunasaw.sip.common.subscribe.SubscribeInfo;
import io.github.lunasaw.sip.common.transmit.request.SipRequestBuilderFactory;
import io.github.lunasaw.sip.common.transmit.strategy.AbstractSipRequestStrategy;
import lombok.extern.slf4j.Slf4j;
import javax.sip.message.Request;
/**
* ACK请求策略实现
*
* @author lin
*/
@Slf4j
public class AckRequestStrategy extends AbstractSipRequestStrategy {
@Override
protected Request buildRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) {
return SipRequestBuilderFactory.createAckRequest(fromDevice, toDevice, content, callId);
}
} | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/impl/NotifyRequestStrategy.java | sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/impl/NotifyRequestStrategy.java | package io.github.lunasaw.sip.common.transmit.strategy.impl;
import io.github.lunasaw.sip.common.entity.FromDevice;
import io.github.lunasaw.sip.common.entity.ToDevice;
import io.github.lunasaw.sip.common.transmit.request.SipRequestBuilderFactory;
import io.github.lunasaw.sip.common.transmit.strategy.AbstractSipRequestStrategy;
import lombok.extern.slf4j.Slf4j;
import javax.sip.message.Request;
/**
* NOTIFY请求策略实现
*
* @author lin
*/
@Slf4j
public class NotifyRequestStrategy extends AbstractSipRequestStrategy {
@Override
protected Request buildRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) {
return SipRequestBuilderFactory.createNotifyRequest(fromDevice, toDevice, content, callId);
}
} | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/impl/RegisterRequestStrategy.java | sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/impl/RegisterRequestStrategy.java | package io.github.lunasaw.sip.common.transmit.strategy.impl;
import io.github.lunasaw.sip.common.entity.FromDevice;
import io.github.lunasaw.sip.common.entity.ToDevice;
import io.github.lunasaw.sip.common.subscribe.SubscribeInfo;
import io.github.lunasaw.sip.common.transmit.request.SipRequestBuilderFactory;
import io.github.lunasaw.sip.common.transmit.strategy.AbstractSipRequestStrategy;
import lombok.extern.slf4j.Slf4j;
import javax.sip.message.Request;
/**
* REGISTER请求策略实现
*
* @author lin
*/
@Slf4j
public class RegisterRequestStrategy extends AbstractSipRequestStrategy {
private final Integer expires;
public RegisterRequestStrategy(Integer expires) {
this.expires = expires;
}
@Override
protected Request buildRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) {
return SipRequestBuilderFactory.createRegisterRequest(fromDevice, toDevice, expires, callId);
}
} | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/impl/SubscribeRequestStrategy.java | sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/impl/SubscribeRequestStrategy.java | package io.github.lunasaw.sip.common.transmit.strategy.impl;
import io.github.lunasaw.sip.common.entity.FromDevice;
import io.github.lunasaw.sip.common.entity.ToDevice;
import io.github.lunasaw.sip.common.subscribe.SubscribeInfo;
import io.github.lunasaw.sip.common.transmit.request.SipRequestBuilderFactory;
import io.github.lunasaw.sip.common.transmit.strategy.AbstractSipRequestStrategy;
import lombok.extern.slf4j.Slf4j;
import javax.sip.message.Request;
/**
* SUBSCRIBE请求策略实现
*
* @author lin
*/
@Slf4j
public class SubscribeRequestStrategy extends AbstractSipRequestStrategy {
@Override
protected Request buildRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) {
return SipRequestBuilderFactory.createSubscribeRequest(fromDevice, toDevice, content, null, callId);
}
@Override
protected Request buildRequestWithSubscribe(FromDevice fromDevice, ToDevice toDevice, String content, SubscribeInfo subscribeInfo, String callId) {
return SipRequestBuilderFactory.createSubscribeRequest(fromDevice, toDevice, content, subscribeInfo, callId);
}
} | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/impl/InfoRequestStrategy.java | sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/impl/InfoRequestStrategy.java | package io.github.lunasaw.sip.common.transmit.strategy.impl;
import io.github.lunasaw.sip.common.entity.FromDevice;
import io.github.lunasaw.sip.common.entity.ToDevice;
import io.github.lunasaw.sip.common.subscribe.SubscribeInfo;
import io.github.lunasaw.sip.common.transmit.request.SipRequestBuilderFactory;
import io.github.lunasaw.sip.common.transmit.strategy.AbstractSipRequestStrategy;
import lombok.extern.slf4j.Slf4j;
import javax.sip.message.Request;
/**
* INFO请求策略实现
*
* @author lin
*/
@Slf4j
public class InfoRequestStrategy extends AbstractSipRequestStrategy {
@Override
protected Request buildRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) {
return SipRequestBuilderFactory.createInfoRequest(fromDevice, toDevice, content, callId);
}
} | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/impl/ByeRequestStrategy.java | sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/impl/ByeRequestStrategy.java | package io.github.lunasaw.sip.common.transmit.strategy.impl;
import io.github.lunasaw.sip.common.entity.FromDevice;
import io.github.lunasaw.sip.common.entity.ToDevice;
import io.github.lunasaw.sip.common.subscribe.SubscribeInfo;
import io.github.lunasaw.sip.common.transmit.request.SipRequestBuilderFactory;
import io.github.lunasaw.sip.common.transmit.strategy.AbstractSipRequestStrategy;
import lombok.extern.slf4j.Slf4j;
import javax.sip.message.Request;
/**
* BYE请求策略实现
*
* @author lin
*/
@Slf4j
public class ByeRequestStrategy extends AbstractSipRequestStrategy {
@Override
protected Request buildRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) {
return SipRequestBuilderFactory.createByeRequest(fromDevice, toDevice, callId);
}
} | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/impl/InviteRequestStrategy.java | sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/strategy/impl/InviteRequestStrategy.java | package io.github.lunasaw.sip.common.transmit.strategy.impl;
import io.github.lunasaw.sip.common.entity.FromDevice;
import io.github.lunasaw.sip.common.entity.ToDevice;
import io.github.lunasaw.sip.common.subscribe.SubscribeInfo;
import io.github.lunasaw.sip.common.transmit.request.SipRequestBuilderFactory;
import io.github.lunasaw.sip.common.transmit.strategy.AbstractSipRequestStrategy;
import lombok.extern.slf4j.Slf4j;
import javax.sip.message.Request;
/**
* INVITE请求策略实现
*
* @author lin
*/
@Slf4j
public class InviteRequestStrategy extends AbstractSipRequestStrategy {
@Override
protected Request buildRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) {
return SipRequestBuilderFactory.createInviteRequest(fromDevice, toDevice, content, null, callId);
}
@Override
protected Request buildRequestWithSubject(FromDevice fromDevice, ToDevice toDevice, String content, String subject, String callId) {
return SipRequestBuilderFactory.createInviteRequest(fromDevice, toDevice, content, subject, callId);
}
} | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/entity/ToDevice.java | sip-common/src/main/java/io/github/lunasaw/sip/common/entity/ToDevice.java | package io.github.lunasaw.sip.common.entity;
import lombok.Data;
/**
* @author luna
* @date 2023/10/12
*/
@Data
public class ToDevice extends Device {
/**
* 及联的处理的时候,需要将上游的toTag往下带
* toTag也是SIP协议中的一个字段,用于标识SIP消息的接收方。每个SIP消息都应该包含一个toTag字段,这个字段的值是由接收方生成的随机字符串,
* 用于标识该消息的接收方。在SIP消息的传输过程中,每个中间节点都会将toTag字段的值保留不变,以确保消息的接收方不变。
*/
private String toTag;
/**
* 需要想下游携带的信息
*/
private String subject;
/**
* 本地ip
*/
private String localIp;
private Integer expires;
private String eventType;
private String eventId;
private String callId;
public static ToDevice getInstance(String userId, String ip, int port) {
ToDevice toDevice = new ToDevice();
toDevice.setUserId(userId);
toDevice.setIp(ip);
toDevice.setPort(port);
toDevice.setTransport("UDP");
toDevice.setStreamMode("TCP_PASSIVE");
toDevice.setToTag(null);
return toDevice;
}
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/entity/SipTransaction.java | sip-common/src/main/java/io/github/lunasaw/sip/common/entity/SipTransaction.java | package io.github.lunasaw.sip.common.entity;
import lombok.Data;
/**
* sip事物交换信息
* @author luna
*/
@Data
public class SipTransaction {
private String callId;
private String fromTag;
private String toTag;
private String viaBranch;
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/entity/ResultDTO.java | sip-common/src/main/java/io/github/lunasaw/sip/common/entity/ResultDTO.java | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false | |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/entity/GbSipDate.java | sip-common/src/main/java/io/github/lunasaw/sip/common/entity/GbSipDate.java | package io.github.lunasaw.sip.common.entity;
import java.util.*;
import gov.nist.core.InternalErrorHandler;
import gov.nist.javax.sip.header.SIPDate;
/**
* 重写jain sip的SIPDate解决与国标时间格式不一致的问题
*
* @author luna
*/
public class GbSipDate extends SIPDate {
/**
*
*/
private static final long serialVersionUID = 1L;
private Calendar javaCal;
public GbSipDate(long timeMillis) {
this.javaCal = new GregorianCalendar(TimeZone.getDefault(), Locale.getDefault());
Date date = new Date(timeMillis);
this.javaCal.setTime(date);
this.wkday = this.javaCal.get(7);
switch (this.wkday) {
case 1:
this.sipWkDay = "Sun";
break;
case 2:
this.sipWkDay = "Mon";
break;
case 3:
this.sipWkDay = "Tue";
break;
case 4:
this.sipWkDay = "Wed";
break;
case 5:
this.sipWkDay = "Thu";
break;
case 6:
this.sipWkDay = "Fri";
break;
case 7:
this.sipWkDay = "Sat";
break;
default:
InternalErrorHandler.handleException("No date map for wkday " + this.wkday);
}
this.day = this.javaCal.get(5);
this.month = this.javaCal.get(2);
switch (this.month) {
case 0:
this.sipMonth = "Jan";
break;
case 1:
this.sipMonth = "Feb";
break;
case 2:
this.sipMonth = "Mar";
break;
case 3:
this.sipMonth = "Apr";
break;
case 4:
this.sipMonth = "May";
break;
case 5:
this.sipMonth = "Jun";
break;
case 6:
this.sipMonth = "Jul";
break;
case 7:
this.sipMonth = "Aug";
break;
case 8:
this.sipMonth = "Sep";
break;
case 9:
this.sipMonth = "Oct";
break;
case 10:
this.sipMonth = "Nov";
break;
case 11:
this.sipMonth = "Dec";
break;
default:
InternalErrorHandler.handleException("No date map for month " + this.month);
}
this.year = this.javaCal.get(1);
this.hour = this.javaCal.get(11);
this.minute = this.javaCal.get(12);
this.second = this.javaCal.get(13);
}
@Override
public StringBuilder encode(StringBuilder var1) {
String var2;
if (this.month < 9) {
var2 = "0" + (this.month + 1);
} else {
var2 = "" + (this.month + 1);
}
String var3;
if (this.day < 10) {
var3 = "0" + this.day;
} else {
var3 = "" + this.day;
}
String var4;
if (this.hour < 10) {
var4 = "0" + this.hour;
} else {
var4 = "" + this.hour;
}
String var5;
if (this.minute < 10) {
var5 = "0" + this.minute;
} else {
var5 = "" + this.minute;
}
String var6;
if (this.second < 10) {
var6 = "0" + this.second;
} else {
var6 = "" + this.second;
}
int var8 = this.javaCal.get(14);
String var7;
if (var8 < 10) {
var7 = "00" + var8;
} else if (var8 < 100) {
var7 = "0" + var8;
} else {
var7 = "" + var8;
}
return var1.append(this.year).append("-").append(var2).append("-").append(var3).append("T").append(var4).append(":").append(var5).append(":").append(var6).append(".").append(var7);
}
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/entity/FromDevice.java | sip-common/src/main/java/io/github/lunasaw/sip/common/entity/FromDevice.java | package io.github.lunasaw.sip.common.entity;
import io.github.lunasaw.sip.common.constant.Constant;
import io.github.lunasaw.sip.common.utils.SipRequestUtils;
import lombok.Data;
/**
* 继承这个类,自定义参数
*
* @author luna
* @date 2023/10/12
*/
@Data
public class FromDevice extends Device {
/**
* fromTag用于标识SIP消息的发送方,每个SIP消息都应该包含一个fromTag字段,这个字段的值是由发送方生成的随机字符串,用于标识该消息的发送方。在SIP消息的传输过程中,每个中间节点都会将fromTag字段的值保留不变,以确保消息的发送方不变。
*/
private String fromTag;
/**
* 发送设备标识 类似浏览器User-Agent
*/
private String agent;
public static FromDevice getInstance(String userId, String ip, int port) {
FromDevice fromDevice = new FromDevice();
fromDevice.setUserId(userId);
fromDevice.setIp(ip);
fromDevice.setPort(port);
fromDevice.setTransport("UDP");
fromDevice.setStreamMode("TCP_PASSIVE");
fromDevice.setFromTag(SipRequestUtils.getNewFromTag());
fromDevice.setAgent(Constant.AGENT);
return fromDevice;
}
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/entity/Device.java | sip-common/src/main/java/io/github/lunasaw/sip/common/entity/Device.java | package io.github.lunasaw.sip.common.entity;
import lombok.Data;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
/**
* @author luna
* @date 2023/10/12
*/
@Data
public abstract class Device {
/**
* 用户Id
*/
private String userId;
/**
* 域
*/
private String realm;
/**
* 传输协议
* UDP/TCP
*/
private String transport;
/**
* 数据流传输模式
* UDP:udp传输
* TCP-ACTIVE:tcp主动模式
* TCP-PASSIVE:tcp被动模式
*/
private String streamMode;
/**
* wan地址_ip
*/
private String ip;
/**
* wan地址_port
*/
private int port;
/**
* wan地址
*/
private String hostAddress;
/**
* 密码
*/
private String password;
/**
* 编码
*/
private String charset;
public String getCharset() {
if (this.charset == null) {
return "UTF-8";
}
return charset;
}
public void setHostAddress(String hostAddress) {
this.hostAddress = hostAddress;
}
public String getHostAddress() {
if (StringUtils.isBlank(hostAddress)) {
return ip + ":" + port;
}
return hostAddress;
}
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/entity/GbSessionDescription.java | sip-common/src/main/java/io/github/lunasaw/sip/common/entity/GbSessionDescription.java | package io.github.lunasaw.sip.common.entity;
import javax.sdp.SessionDescription;
import lombok.Data;
/**
* 28181 的SDP解析器
*
* @author luna
*/
@Data
public class GbSessionDescription extends SdpSessionDescription {
private String ssrc;
private String mediaDescription;
/**
* 冗余处理
*/
private String address;
private Integer port;
public GbSessionDescription(SessionDescription sessionDescription) {
super(sessionDescription);
}
public static GbSessionDescription getInstance(SessionDescription sessionDescription, String ssrc, String mediaDescription) {
GbSessionDescription gbSessionDescription = new GbSessionDescription(sessionDescription);
gbSessionDescription.setSsrc(ssrc);
gbSessionDescription.setMediaDescription(mediaDescription);
return gbSessionDescription;
}
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/entity/RemoteAddressInfo.java | sip-common/src/main/java/io/github/lunasaw/sip/common/entity/RemoteAddressInfo.java | package io.github.lunasaw.sip.common.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author luna
*/
@AllArgsConstructor
@NoArgsConstructor
@Data
public class RemoteAddressInfo {
private String ip;
private Integer port;
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/entity/DeviceSession.java | sip-common/src/main/java/io/github/lunasaw/sip/common/entity/DeviceSession.java | package io.github.lunasaw.sip.common.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author luna
* @date 2023/10/20
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class DeviceSession {
String userId;
String sipId;
public DeviceSession(String userId, String sipId) {
this.userId = userId;
this.sipId = sipId;
}
private FromDevice fromDevice;
private ToDevice toDevice;
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/entity/SipMessage.java | sip-common/src/main/java/io/github/lunasaw/sip/common/entity/SipMessage.java | package io.github.lunasaw.sip.common.entity;
import java.util.List;
import javax.sip.header.ContentTypeHeader;
import javax.sip.header.Header;
import javax.sip.message.Request;
import org.apache.commons.collections4.CollectionUtils;
import org.assertj.core.util.Lists;
import gov.nist.javax.sip.message.SIPResponse;
import io.github.lunasaw.sip.common.enums.ContentTypeEnum;
import io.github.lunasaw.sip.common.sequence.GenerateSequenceImpl;
import io.github.lunasaw.sip.common.utils.SipRequestUtils;
import lombok.Data;
/**
* @author luna
* @date 2023/10/13
*/
@Data
public class SipMessage {
/**
* 单次请求唯一标识 可以使用时间戳 自增即可
*/
private Long sequence;
/**
* 事物响应唯一标识 作为同一个请求判断
*/
private String callId;
/**
* sip请求 方式
*/
private String method;
/**
* 单次sip请求唯一标识
* viaTag用于标识SIP消息的唯一性,每个SIP消息都应该包含一个viaTag字段,这个字段的值是由发送方生成的随机字符串,用于标识该消息的唯一性。在SIP消息的传输过程中,每个中间节点都会将viaTag字段的值更新为自己生成的随机字符串,以确保消息的唯一性。
*/
private String viaTag;
/**
* sip请求 内容
*/
private String content;
/**
* sip请求 请求类型
*/
private ContentTypeHeader contentTypeHeader;
/**
* 自定义header
*/
private List<Header> headers;
/**
* 响应状态码
*/
private Integer statusCode;
public static SipMessage getMessageBody() {
SipMessage sipMessage = new SipMessage();
sipMessage.setMethod(Request.MESSAGE);
sipMessage.setContentTypeHeader(ContentTypeEnum.APPLICATION_XML.getContentTypeHeader());
sipMessage.setViaTag(SipRequestUtils.getNewViaTag());
long sequence = GenerateSequenceImpl.getSequence();
sipMessage.setSequence(sequence);
return sipMessage;
}
public static SipMessage getInviteBody() {
SipMessage sipMessage = new SipMessage();
sipMessage.setMethod(Request.INVITE);
sipMessage.setContentTypeHeader(ContentTypeEnum.APPLICATION_SDP.getContentTypeHeader());
sipMessage.setViaTag(SipRequestUtils.getNewViaTag());
long sequence = GenerateSequenceImpl.getSequence();
sipMessage.setSequence(sequence);
return sipMessage;
}
public static SipMessage getByeBody() {
SipMessage sipMessage = new SipMessage();
sipMessage.setMethod(Request.BYE);
sipMessage.setViaTag(SipRequestUtils.getNewViaTag());
long sequence = GenerateSequenceImpl.getSequence();
sipMessage.setSequence(sequence);
return sipMessage;
}
public static SipMessage getSubscribeBody() {
SipMessage sipMessage = new SipMessage();
sipMessage.setMethod(Request.SUBSCRIBE);
sipMessage.setContentTypeHeader(ContentTypeEnum.APPLICATION_XML.getContentTypeHeader());
sipMessage.setViaTag(SipRequestUtils.getNewViaTag());
long sequence = GenerateSequenceImpl.getSequence();
sipMessage.setSequence(sequence);
return sipMessage;
}
public static SipMessage getInfoBody() {
SipMessage sipMessage = new SipMessage();
sipMessage.setMethod(Request.INFO);
sipMessage.setContentTypeHeader(ContentTypeEnum.APPLICATION_MAN_SRTSP.getContentTypeHeader());
sipMessage.setViaTag(SipRequestUtils.getNewViaTag());
long sequence = GenerateSequenceImpl.getSequence();
sipMessage.setSequence(sequence);
return sipMessage;
}
public static SipMessage getNotifyBody() {
SipMessage sipMessage = new SipMessage();
sipMessage.setMethod(Request.NOTIFY);
sipMessage.setContentTypeHeader(ContentTypeEnum.APPLICATION_XML.getContentTypeHeader());
sipMessage.setViaTag(SipRequestUtils.getNewViaTag());
long sequence = GenerateSequenceImpl.getSequence();
sipMessage.setSequence(sequence);
return sipMessage;
}
public static SipMessage getAckBody(SIPResponse sipResponse) {
SipMessage sipMessage = new SipMessage();
sipMessage.setMethod(Request.ACK);
sipMessage.setViaTag(SipRequestUtils.getNewViaTag());
sipMessage.setSequence(sipResponse.getCSeqHeader().getSeqNumber());
return sipMessage;
}
public static SipMessage getAckBody() {
SipMessage sipMessage = new SipMessage();
sipMessage.setMethod(Request.ACK);
sipMessage.setViaTag(SipRequestUtils.getNewViaTag());
long sequence = GenerateSequenceImpl.getSequence();
sipMessage.setSequence(sequence);
return sipMessage;
}
public static SipMessage getRegisterBody() {
SipMessage sipMessage = new SipMessage();
sipMessage.setMethod(Request.REGISTER);
sipMessage.setViaTag(SipRequestUtils.getNewViaTag());
long sequence = GenerateSequenceImpl.getSequence();
sipMessage.setSequence(sequence);
return sipMessage;
}
public static SipMessage getResponse(int statusCode) {
SipMessage sipMessage = new SipMessage();
sipMessage.setViaTag(SipRequestUtils.getNewViaTag());
long sequence = GenerateSequenceImpl.getSequence();
sipMessage.setStatusCode(statusCode);
sipMessage.setSequence(sequence);
return sipMessage;
}
public SipMessage addHeader(Header header) {
if (CollectionUtils.isEmpty(headers)) {
headers = Lists.newArrayList(header);
} else {
headers.add(header);
}
return this;
}
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/entity/SdpSessionDescription.java | sip-common/src/main/java/io/github/lunasaw/sip/common/entity/SdpSessionDescription.java | package io.github.lunasaw.sip.common.entity;
import javax.sdp.SessionDescription;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* SDP解析器
*
* @author luna
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SdpSessionDescription {
/**
* 会话描述表示由会话描述协议(请参阅 IETF RFC 2327)定义的数据
*/
private SessionDescription baseSdb;
public static SdpSessionDescription getInstance(SessionDescription sdp) {
SdpSessionDescription sdpSessionDescription = new SdpSessionDescription();
sdpSessionDescription.setBaseSdb(sdp);
return sdpSessionDescription;
}
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/config/SipCommonProperties.java | sip-common/src/main/java/io/github/lunasaw/sip/common/config/SipCommonProperties.java | package io.github.lunasaw.sip.common.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* GB28181通用配置属性类 - 支持外部化配置
* 包含通用的性能配置和缓存配置,client和server特定配置已拆分到各自模块
*
* @author luna
* @date 2024/1/6
*/
@Data
@Component
@ConfigurationProperties(prefix = "sip.common")
public class SipCommonProperties {
/**
* 时间同步配置
*/
private TimeSync timeSync = new TimeSync();
/**
* 时间同步方式枚举
*/
public enum TimeSyncMode {
/**
* 仅使用SIP校时
*/
SIP,
/**
* 仅使用NTP校时
*/
NTP,
/**
* 同时使用SIP和NTP校时
*/
BOTH
}
/**
* 时间同步配置
*/
@Data
public static class TimeSync {
/**
* 是否启用时间同步
*/
private boolean enabled = true;
/**
* 时间同步方式: SIP, NTP, BOTH
*/
private TimeSyncMode mode = TimeSyncMode.SIP;
/**
* 时间偏差阈值(毫秒)
* 当时间偏差超过此值时会记录警告
*/
private long offsetThreshold = 1000;
/**
* NTP服务器地址
*/
private String ntpServer = "pool.ntp.org";
/**
* NTP校时间隔(秒)
*/
private long ntpSyncInterval = 3600;
/**
* SIP注册过期时间建议值(秒)
* 当时间偏差超过阈值时的注册过期时间
*/
private int registerExpireOnError = 36000;
/**
* 是否在时间偏差较大时自动调整注册过期时间
*/
private boolean autoAdjustExpire = true;
}
} | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/config/MetricsConfig.java | sip-common/src/main/java/io/github/lunasaw/sip/common/config/MetricsConfig.java | package io.github.lunasaw.sip.common.config;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 监控指标配置类
* 当Spring容器中没有MeterRegistry Bean时,自动提供一个SimpleMeterRegistry
*
* @author luna
* @date 2024/1/6
*/
@Configuration
public class MetricsConfig {
/**
* 提供MeterRegistry Bean
* 当Spring容器中没有MeterRegistry Bean时,自动提供一个SimpleMeterRegistry
* 这样可以确保SipMetrics类能够正常工作
*/
@Bean
@ConditionalOnMissingBean(MeterRegistry.class)
public MeterRegistry meterRegistry() {
return new SimpleMeterRegistry();
}
} | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/sequence/GenerateSequenceImpl.java | sip-common/src/main/java/io/github/lunasaw/sip/common/sequence/GenerateSequenceImpl.java | package io.github.lunasaw.sip.common.sequence;
import lombok.SneakyThrows;
import java.util.HashSet;
import java.util.Set;
/**
* @author luna
* @date 2023/10/13
*/
public class GenerateSequenceImpl implements GenerateSequence {
public static long getSequence() {
long timestamp = System.currentTimeMillis();
return (timestamp & 0x3FFF) % Integer.MAX_VALUE;
}
@Override
public Long generateSequence() {
return getSequence();
}
@SneakyThrows
public static void main(String[] args) {
Set<Long> list = new HashSet<>();
for (int i = 0; i < 10000; i++) {
Thread.sleep(1);
long sequence = getSequence();
System.out.println(sequence);
list.add(sequence);
}
System.out.println(list.size());
}
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/sequence/GenerateSequence.java | sip-common/src/main/java/io/github/lunasaw/sip/common/sequence/GenerateSequence.java | package io.github.lunasaw.sip.common.sequence;
/**
* @author luna
* @date 2023/10/13
*/
public interface GenerateSequence {
/**
* 生成唯一序列
*
* @return
*/
Long generateSequence();
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/conf/StackLoggerImpl.java | sip-common/src/main/java/io/github/lunasaw/sip/common/conf/StackLoggerImpl.java | package io.github.lunasaw.sip.common.conf;
import java.util.Properties;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LocationAwareLogger;
import org.springframework.stereotype.Component;
import gov.nist.core.StackLogger;
@Component
public class StackLoggerImpl implements StackLogger {
/**
* 完全限定类名(Fully Qualified Class Name),用于定位日志位置
*/
private static final String FQCN = StackLoggerImpl.class.getName();
/**
* 获取栈中类信息(以便底层日志记录系统能够提取正确的位置信息(方法名、行号))
*
* @return LocationAwareLogger
*/
private static LocationAwareLogger getLocationAwareLogger() {
return (LocationAwareLogger)LoggerFactory.getLogger(new Throwable().getStackTrace()[4].getClassName());
}
/**
* 封装打印日志的位置信息
*
* @param level 日志级别
* @param message 日志事件的消息
*/
private static void log(int level, String message) {
LocationAwareLogger locationAwareLogger = getLocationAwareLogger();
locationAwareLogger.log(null, FQCN, level, message, null, null);
}
/**
* 封装打印日志的位置信息
*
* @param level 日志级别
* @param message 日志事件的消息
*/
private static void log(int level, String message, Throwable throwable) {
LocationAwareLogger locationAwareLogger = getLocationAwareLogger();
locationAwareLogger.log(null, FQCN, level, message, null, throwable);
}
@Override
public void logStackTrace() {
}
@Override
public void logStackTrace(int traceLevel) {
System.out.println("traceLevel: " + traceLevel);
}
@Override
public int getLineCount() {
return 0;
}
@Override
public void logException(Throwable ex) {
}
@Override
public void logDebug(String message) {
// log(LocationAwareLogger.INFO_INT, message);
}
@Override
public void logDebug(String message, Exception ex) {
// log(LocationAwareLogger.INFO_INT, message, ex);
}
@Override
public void logTrace(String message) {
log(LocationAwareLogger.INFO_INT, message);
}
@Override
public void logFatalError(String message) {
log(LocationAwareLogger.INFO_INT, message);
}
@Override
public void logError(String message) {
log(LocationAwareLogger.INFO_INT, message);
}
@Override
public boolean isLoggingEnabled() {
return true;
}
@Override
public boolean isLoggingEnabled(int logLevel) {
return true;
}
@Override
public void logError(String message, Exception ex) {
log(LocationAwareLogger.INFO_INT, message, ex);
}
@Override
public void logWarning(String message) {
log(LocationAwareLogger.INFO_INT, message);
}
@Override
public void logInfo(String message) {
log(LocationAwareLogger.INFO_INT, message);
}
@Override
public void disableLogging() {
}
@Override
public void enableLogging() {
}
@Override
public void setBuildTimeStamp(String buildTimeStamp) {
}
@Override
public void setStackProperties(Properties stackProperties) {
}
@Override
public String getLoggerName() {
return null;
}
} | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/conf/package-info.java | sip-common/src/main/java/io/github/lunasaw/sip/common/conf/package-info.java | /**
* Contains classes for configuring the SIP stack.
* 包含配置SIP栈的类
*
* @author luna
* @date 2023/11/20
*/
package io.github.lunasaw.sip.common.conf; | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/conf/ServerLoggerImpl.java | sip-common/src/main/java/io/github/lunasaw/sip/common/conf/ServerLoggerImpl.java | package io.github.lunasaw.sip.common.conf;
import java.util.Properties;
import javax.sip.SipStack;
import gov.nist.core.CommonLogger;
import gov.nist.core.ServerLogger;
import gov.nist.core.StackLogger;
import gov.nist.javax.sip.message.SIPMessage;
import gov.nist.javax.sip.stack.SIPTransactionStack;
public class ServerLoggerImpl implements ServerLogger {
protected StackLogger stackLogger;
private boolean showLog = true;
private SIPTransactionStack sipStack;
@Override
public void closeLogFile() {
}
@Override
public void logMessage(SIPMessage message, String from, String to, boolean sender, long time) {
if (!showLog) {
return;
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(sender ? from + "发送:目标--->" + to : to + " 接收:来自--->" + from)
.append("\r\n")
.append(message);
this.stackLogger.logInfo(stringBuilder.toString());
}
@Override
public void logMessage(SIPMessage message, String from, String to, String status, boolean sender, long time) {
}
@Override
public void logMessage(SIPMessage message, String from, String to, String status, boolean sender) {
}
@Override
public void logException(Exception ex) {
if (!showLog) {
return;
}
this.stackLogger.logException(ex);
}
@Override
public void setStackProperties(Properties stackProperties) {
if (!showLog) {
return;
}
String TRACE_LEVEL = stackProperties.getProperty("gov.nist.javax.sip.TRACE_LEVEL");
if (TRACE_LEVEL != null) {
showLog = true;
}
}
@Override
public void setSipStack(SipStack sipStack) {
if (!showLog) {
return;
}
if (sipStack instanceof SIPTransactionStack) {
this.sipStack = (SIPTransactionStack) sipStack;
this.stackLogger = CommonLogger.getLogger(SIPTransactionStack.class);
}
}
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/conf/DefaultProperties.java | sip-common/src/main/java/io/github/lunasaw/sip/common/conf/DefaultProperties.java | package io.github.lunasaw.sip.common.conf;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Properties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;
import lombok.extern.slf4j.Slf4j;
/**
* 获取sip默认配置
* 完整配置参考 gov.nist.javax.sip.SipStackImpl,需要下载源码
* gov/nist/javax/sip/SipStackImpl.class
* sip消息的解析在 gov.nist.javax.sip.stack.UDPMessageChannel的processIncomingDataPacket 方法
*
* @author luna
*/
@Slf4j
public class DefaultProperties {
public static Properties getProperties(String name, String ip, boolean sipLog) {
Properties properties = new Properties();
properties.setProperty("javax.sip.STACK_NAME", name);
properties.setProperty("javax.sip.IP_ADDRESS", ip);
/**
* sip_server_log.log 和 sip_debug_log.log ERROR, INFO, WARNING, OFF, DEBUG, TRACE
*/
try {
Resource resource = new ClassPathResource("sip/config.properties");
InputStream inputStream = resource.getInputStream();
properties.load(inputStream);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (sipLog) {
properties.setProperty("gov.nist.javax.sip.STACK_LOGGER", "io.github.lunasaw.sip.common.conf.StackLoggerImpl");
properties.setProperty("gov.nist.javax.sip.SERVER_LOGGER", "io.github.lunasaw.sip.common.conf.ServerLoggerImpl");
properties.setProperty("gov.nist.javax.sip.LOG_MESSAGE_CONTENT", "true");
log.info("[SIP日志]已开启");
} else {
log.info("[SIP日志]已关闭");
}
return properties;
}
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/conf/SipProxyAutoConfig.java | sip-common/src/main/java/io/github/lunasaw/sip/common/conf/SipProxyAutoConfig.java | package io.github.lunasaw.sip.common.conf;
import io.github.lunasaw.sip.common.transmit.CustomerSipListener;
import io.github.lunasaw.sip.common.transmit.event.request.SipRequestProcessor;
import io.github.lunasaw.sip.common.transmit.event.request.SipRequestProcessorAbstract;
import io.github.lunasaw.sip.common.transmit.event.response.AbstractSipResponseProcessor;
import io.github.lunasaw.sip.common.transmit.event.response.SipResponseProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import javax.sip.SipListener;
import java.lang.reflect.Field;
import java.util.Map;
/**
* SIP代理自动配置类
* 使用新的注册表机制管理响应处理器,实现框架和业务分离
*
* @author luna
*/
@Slf4j
@ComponentScan("io.github.lunasaw.sip.common")
@Configuration
public class SipProxyAutoConfig implements InitializingBean, ApplicationContextAware {
private static final String METHOD = "method";
private ApplicationContext applicationContext;
@Bean
@ConditionalOnMissingBean
public SipListener sipListener() {
// 默认使用同步监听器,可以通过配置切换为异步监听器
return CustomerSipListener.getInstance();
}
@Override
public void afterPropertiesSet() {
// 注册所有响应处理器
registerResponseProcessors();
// 注册所有请求处理器
registerRequestProcessors();
}
/**
* 注册响应处理器
* 使用新的注册表机制,支持策略组合
*/
private void registerResponseProcessors() {
Map<String, SipResponseProcessor> processorMap =
applicationContext.getBeansOfType(SipResponseProcessor.class);
processorMap.forEach((beanName, processor) -> {
try {
if (processor instanceof AbstractSipResponseProcessor) {
AbstractSipResponseProcessor abstractProcessor = (AbstractSipResponseProcessor) processor;
String method = abstractProcessor.getMethod();
CustomerSipListener.getInstance().addResponseProcessor(method, abstractProcessor);
log.info("注册响应处理器: {} -> {}", method, processor.getClass().getSimpleName());
}
} catch (Exception e) {
log.error("注册响应处理器失败: bean = {}", beanName, e);
}
});
log.info("注册响应处理器完成: {} 个处理器", processorMap.size());
}
/**
* 注册请求处理器
* 保持原有的请求处理器注册逻辑
*/
private void registerRequestProcessors() {
Map<String, SipRequestProcessor> requestProcessorMap =
applicationContext.getBeansOfType(SipRequestProcessor.class);
requestProcessorMap.forEach((beanName, processor) -> {
try {
if (processor instanceof SipRequestProcessorAbstract) {
Field field = processor.getClass().getDeclaredField(METHOD);
field.setAccessible(true);
String method = field.get(processor).toString();
CustomerSipListener.getInstance().addRequestProcessor(method, processor);
log.info("注册请求处理器: {} -> {}", method, processor.getClass().getSimpleName());
}
} catch (Exception e) {
log.error("注册请求处理器失败: bean = {}", beanName, e);
}
});
log.info("注册请求处理器完成: {} 个处理器", requestProcessorMap.size());
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/conf/ThreadPoolTaskConfig.java | sip-common/src/main/java/io/github/lunasaw/sip/common/conf/ThreadPoolTaskConfig.java | package io.github.lunasaw.sip.common.conf;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* ThreadPoolTask 配置类 - 优化版本
*
* @author lin
*/
@Configuration
@Order(1)
@EnableAsync(proxyTargetClass = true)
public class ThreadPoolTaskConfig {
public static final int cpuNum = Runtime.getRuntime().availableProcessors();
@Value("${sip.shutdown.await-termination-seconds:30}")
private int awaitTerminationSeconds;
/**
* 默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,
* 当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中;
* 当队列满了,就继续创建线程,当线程数量大于等于maxPoolSize后,开始使用拒绝策略拒绝
*/
/**
* 动态计算核心线程数(CPU密集型任务:CPU核心数+1,IO密集型任务:CPU核心数*2)
*/
private static final int corePoolSize = cpuNum * 2;
/**
* 最大线程数(IO密集型任务:CPU核心数*4)
*/
private static final int maxPoolSize = cpuNum * 4;
/**
* 允许线程空闲时间(单位:默认为秒)
*/
private static final int keepAliveTime = 60;
/**
* 缓冲队列大小(增大队列容量)
*/
private static final int queueCapacity = 1000;
/**
* 线程池名前缀
*/
private static final String threadNamePrefix = "sip-";
/**
* SIP消息处理专用线程池
*/
@Bean("sipMessageProcessor")
public ThreadPoolTaskExecutor sipMessageProcessor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveTime);
executor.setThreadNamePrefix("sip-msg-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(awaitTerminationSeconds);
executor.initialize();
return executor;
}
/**
* SIP定时任务线程池
*/
@Bean("sipScheduledExecutor")
public ScheduledThreadPoolExecutor sipScheduledExecutor() {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(
cpuNum,
new ThreadFactoryBuilder()
.setNameFormat("sip-scheduled-%d")
.setDaemon(true)
.build());
executor.setMaximumPoolSize(cpuNum * 2);
executor.setKeepAliveTime(60, java.util.concurrent.TimeUnit.SECONDS);
executor.allowCoreThreadTimeOut(true);
return executor;
}
/**
* 兼容性保留 - 原有的sipTaskExecutor
*/
@Bean("sipTaskExecutor") // bean的名称,默认为首字母小写的方法名
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveTime);
executor.setThreadNamePrefix(threadNamePrefix);
// 线程池对拒绝任务的处理策略
// CallerRunsPolicy:由调用线程(提交任务的线程)处理该任务
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(awaitTerminationSeconds);
// 初始化
executor.initialize();
return executor;
}
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/conf/msg/StringMsgParser.java | sip-common/src/main/java/io/github/lunasaw/sip/common/conf/msg/StringMsgParser.java | package io.github.lunasaw.sip.common.conf.msg;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import gov.nist.core.CommonLogger;
import gov.nist.core.Host;
import gov.nist.core.HostNameParser;
import gov.nist.core.StackLogger;
import gov.nist.javax.sip.SIPConstants;
import gov.nist.javax.sip.address.AddressImpl;
import gov.nist.javax.sip.address.GenericURI;
import gov.nist.javax.sip.address.SipUri;
import gov.nist.javax.sip.address.TelephoneNumber;
import gov.nist.javax.sip.header.*;
import gov.nist.javax.sip.message.SIPMessage;
import gov.nist.javax.sip.message.SIPRequest;
import gov.nist.javax.sip.message.SIPResponse;
import gov.nist.javax.sip.parser.*;
public class StringMsgParser implements MessageParser {
protected static boolean computeContentLengthFromMessage = false;
private static StackLogger logger = CommonLogger.getLogger(gov.nist.javax.sip.parser.StringMsgParser.class);
/**
* @since v0.9
*/
public StringMsgParser() {
super();
}
/**
* Parse a buffer containing a single SIP Message where the body is an array
* of un-interpreted bytes. This is intended for parsing the message from a
* memory buffer when the buffer. Incorporates a bug fix for a bug that was
* noted by Will Sullin of Callcast
*
* @param msgBuffer a byte buffer containing the messages to be parsed. This can
* consist of multiple SIP Messages concatenated together.
* @return a SIPMessage[] structure (request or response) containing the
* parsed SIP message.
* @throws ParseException is thrown when an illegal message has been encountered
* (and the rest of the buffer is discarded).
* @see ParseExceptionListener
*/
public SIPMessage parseSIPMessage(byte[] msgBuffer, boolean readBody, boolean strict, ParseExceptionListener parseExceptionListener) throws ParseException {
if (msgBuffer == null || msgBuffer.length == 0)
return null;
int i = 0;
// Squeeze out any leading control character.
try {
while (msgBuffer[i] < 0x20)
i++;
} catch (ArrayIndexOutOfBoundsException e) {
// Array contains only control char, return null.
if (logger.isLoggingEnabled(StackLogger.TRACE_DEBUG)) {
logger.logDebug("handled only control char so returning null");
}
return null;
}
// Iterate thru the request/status line and headers.
String currentLine = null;
String currentHeader = null;
boolean isFirstLine = true;
SIPMessage message = null;
do {
int lineStart = i;
// Find the length of the line.
try {
while (msgBuffer[i] != '\r' && msgBuffer[i] != '\n')
i++;
} catch (ArrayIndexOutOfBoundsException e) {
// End of the message.
break;
}
int lineLength = i - lineStart;
// Make it a String.
currentLine = new String(msgBuffer, lineStart, lineLength, StandardCharsets.UTF_8);
currentLine = trimEndOfLine(currentLine);
if (currentLine.length() == 0) {
// Last header line, process the previous buffered header.
if (currentHeader != null && message != null) {
processHeader(currentHeader, message, parseExceptionListener, msgBuffer);
}
} else {
if (isFirstLine) {
message = processFirstLine(currentLine, parseExceptionListener, msgBuffer);
} else {
char firstChar = currentLine.charAt(0);
if (firstChar == '\t' || firstChar == ' ') {
if (currentHeader == null)
throw new ParseException("Bad header continuation.", 0);
// This is a continuation, append it to the previous line.
currentHeader += currentLine.substring(1);
} else {
if (currentHeader != null && message != null) {
processHeader(currentHeader, message, parseExceptionListener, msgBuffer);
}
currentHeader = currentLine;
}
}
}
if (msgBuffer[i] == '\r' && msgBuffer.length > i + 1 && msgBuffer[i + 1] == '\n')
i++;
i++;
isFirstLine = false;
} while (currentLine.length() > 0); // End do - while
if (message == null) throw new ParseException("Bad message", 0);
message.setSize(i);
// Check for content legth header
if (readBody && message.getContentLength() != null) {
if (message.getContentLength().getContentLength() != 0) {
int bodyLength = msgBuffer.length - i;
byte[] body = new byte[bodyLength];
System.arraycopy(msgBuffer, i, body, 0, bodyLength);
message.setMessageContent(body, !strict, computeContentLengthFromMessage, message.getContentLength().getContentLength());
} else if (message.getCSeqHeader().getMethod().equalsIgnoreCase("MESSAGE")) {
int bodyLength = msgBuffer.length - i;
byte[] body = new byte[bodyLength];
System.arraycopy(msgBuffer, i, body, 0, bodyLength);
message.setMessageContent(body, !strict, computeContentLengthFromMessage, bodyLength);
} else if (!computeContentLengthFromMessage && strict) {
String last4Chars = new String(msgBuffer, msgBuffer.length - 4, 4);
if (!"\r\n\r\n".equals(last4Chars)) {
throw new ParseException("Extraneous characters at the end of the message ", i);
}
}
}
return message;
}
protected static String trimEndOfLine(String line) {
if (line == null)
return line;
int i = line.length() - 1;
while (i >= 0 && line.charAt(i) <= 0x20)
i--;
if (i == line.length() - 1)
return line;
if (i == -1)
return "";
return line.substring(0, i + 1);
}
protected SIPMessage processFirstLine(String firstLine, ParseExceptionListener parseExceptionListener, byte[] msgBuffer) throws ParseException {
SIPMessage message;
if (!firstLine.startsWith(SIPConstants.SIP_VERSION_STRING)) {
message = new SIPRequest();
try {
RequestLine requestLine = new RequestLineParser(firstLine + "\n")
.parse();
((SIPRequest) message).setRequestLine(requestLine);
} catch (ParseException ex) {
if (parseExceptionListener != null)
try {
parseExceptionListener.handleException(ex, message,
RequestLine.class, firstLine, new String(msgBuffer, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
else
throw ex;
}
} else {
message = new SIPResponse();
try {
StatusLine sl = new StatusLineParser(firstLine + "\n").parse();
((SIPResponse) message).setStatusLine(sl);
} catch (ParseException ex) {
if (parseExceptionListener != null) {
try {
parseExceptionListener.handleException(ex, message,
StatusLine.class, firstLine, new String(msgBuffer, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else
throw ex;
}
}
return message;
}
protected void processHeader(String header, SIPMessage message, ParseExceptionListener parseExceptionListener, byte[] rawMessage) throws ParseException {
if (header == null || header.length() == 0)
return;
HeaderParser headerParser = null;
try {
headerParser = ParserFactory.createParser(header + "\n");
} catch (ParseException ex) {
// https://java.net/jira/browse/JSIP-456
if (parseExceptionListener != null) {
parseExceptionListener.handleException(ex, message, null,
header, null);
return;
} else {
throw ex;
}
}
try {
SIPHeader sipHeader = headerParser.parse();
message.attachHeader(sipHeader, false);
} catch (ParseException ex) {
if (parseExceptionListener != null) {
String headerName = Lexer.getHeaderName(header);
Class headerClass = NameMap.getClassFromName(headerName);
if (headerClass == null) {
headerClass = ExtensionHeaderImpl.class;
}
try {
parseExceptionListener.handleException(ex, message,
headerClass, header, new String(rawMessage, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
/**
* Parse an address (nameaddr or address spec) and return and address
* structure.
*
* @param address is a String containing the address to be parsed.
* @return a parsed address structure.
* @throws ParseException when the address is badly formatted.
* @since v1.0
*/
public AddressImpl parseAddress(String address) throws ParseException {
AddressParser addressParser = new AddressParser(address);
return addressParser.address(true);
}
/**
* Parse a host:port and return a parsed structure.
*
* @param hostport
* is a String containing the host:port to be parsed
* @return a parsed address structure.
* @since v1.0
* @exception throws
* a ParseException when the address is badly formatted.
*
public HostPort parseHostPort(String hostport) throws ParseException {
Lexer lexer = new Lexer("charLexer", hostport);
return new HostNameParser(lexer).hostPort();
}
*/
/**
* Parse a host name and return a parsed structure.
*
* @param host is a String containing the host name to be parsed
* @return a parsed address structure.
* @throws ParseException a ParseException when the hostname is badly formatted.
* @since v1.0
*/
public Host parseHost(String host) throws ParseException {
Lexer lexer = new Lexer("charLexer", host);
return new HostNameParser(lexer).host();
}
/**
* Parse a telephone number return a parsed structure.
*
* @param telephone_number is a String containing the telephone # to be parsed
* @return a parsed address structure.
* @throws ParseException a ParseException when the address is badly formatted.
* @since v1.0
*/
public TelephoneNumber parseTelephoneNumber(String telephone_number)
throws ParseException {
// Bug fix contributed by Will Scullin
return new URLParser(telephone_number).parseTelephoneNumber(true);
}
/**
* Parse a SIP url from a string and return a URI structure for it.
*
* @param url a String containing the URI structure to be parsed.
* @return A parsed URI structure
* @throws ParseException if there was an error parsing the message.
*/
public SipUri parseSIPUrl(String url) throws ParseException {
try {
return new URLParser(url).sipURL(true);
} catch (ClassCastException ex) {
throw new ParseException(url + " Not a SIP URL ", 0);
}
}
/**
* Parse a uri from a string and return a URI structure for it.
*
* @param url a String containing the URI structure to be parsed.
* @return A parsed URI structure
* @throws ParseException if there was an error parsing the message.
*/
public GenericURI parseUrl(String url) throws ParseException {
return new URLParser(url).parse();
}
/**
* Parse an individual SIP message header from a string.
*
* @param header String containing the SIP header.
* @return a SIPHeader structure.
* @throws ParseException if there was an error parsing the message.
*/
public static SIPHeader parseSIPHeader(String header) throws ParseException {
int start = 0;
int end = header.length() - 1;
try {
// Squeeze out any leading control character.
while (header.charAt(start) <= 0x20)
start++;
// Squeeze out any trailing control character.
while (header.charAt(end) <= 0x20)
end--;
} catch (ArrayIndexOutOfBoundsException e) {
// Array contains only control char.
throw new ParseException("Empty header.", 0);
}
StringBuilder buffer = new StringBuilder(end + 1);
int i = start;
int lineStart = start;
boolean endOfLine = false;
while (i <= end) {
char c = header.charAt(i);
if (c == '\r' || c == '\n') {
if (!endOfLine) {
buffer.append(header.substring(lineStart, i));
endOfLine = true;
}
} else {
if (endOfLine) {
endOfLine = false;
if (c == ' ' || c == '\t') {
buffer.append(' ');
lineStart = i + 1;
} else {
lineStart = i;
}
}
}
i++;
}
buffer.append(header.substring(lineStart, i));
buffer.append('\n');
HeaderParser hp = ParserFactory.createParser(buffer.toString());
if (hp == null)
throw new ParseException("could not create parser", 0);
return hp.parse();
}
/**
* Parse the SIP Request Line
*
* @param requestLine a String containing the request line to be parsed.
* @return a RequestLine structure that has the parsed RequestLine
* @throws ParseException if there was an error parsing the requestLine.
*/
public RequestLine parseSIPRequestLine(String requestLine)
throws ParseException {
requestLine += "\n";
return new RequestLineParser(requestLine).parse();
}
/**
* Parse the SIP Response message status line
*
* @param statusLine a String containing the Status line to be parsed.
* @return StatusLine class corresponding to message
* @throws ParseException if there was an error parsing
* @see StatusLine
*/
public StatusLine parseSIPStatusLine(String statusLine)
throws ParseException {
statusLine += "\n";
return new StatusLineParser(statusLine).parse();
}
public static void setComputeContentLengthFromMessage(
boolean computeContentLengthFromMessage) {
StringMsgParser.computeContentLengthFromMessage = computeContentLengthFromMessage;
}
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/conf/msg/StringMsgParserFactory.java | sip-common/src/main/java/io/github/lunasaw/sip/common/conf/msg/StringMsgParserFactory.java | package io.github.lunasaw.sip.common.conf.msg;
import gov.nist.javax.sip.parser.MessageParser;
import gov.nist.javax.sip.parser.MessageParserFactory;
import gov.nist.javax.sip.stack.SIPTransactionStack;
public class StringMsgParserFactory implements MessageParserFactory {
/**
* msg parser is completely stateless, reuse isntance for the whole stack
* fixes https://github.com/RestComm/jain-sip/issues/92
*/
private static StringMsgParser msgParser = new StringMsgParser();
/*
* (non-Javadoc)
* @see gov.nist.javax.sip.parser.MessageParserFactory#createMessageParser(gov.nist.javax.sip.stack.SIPTransactionStack)
*/
public MessageParser createMessageParser(SIPTransactionStack stack) {
return msgParser;
}
}
| java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/context/SipTransactionContext.java | sip-common/src/main/java/io/github/lunasaw/sip/common/context/SipTransactionContext.java | package io.github.lunasaw.sip.common.context;
import javax.sip.RequestEvent;
import javax.sip.header.CSeqHeader;
import javax.sip.header.CallIdHeader;
import javax.sip.header.FromHeader;
import javax.sip.header.ToHeader;
import javax.sip.message.Request;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
/**
* SIP事务上下文管理器
* 通过ThreadLocal管理完整的SIP事务上下文,包括Call-ID、CSeq、From/To头部等
* 确保请求-响应-ACK整个链路使用相同的事务参数
* <p>
* 支持两种模式:
* 1. 显式模式:通过setRequestEvent直接设置原始请求事件,自动提取事务参数
* 2. 隐式模式:通过setTransactionInfo设置完整事务信息,在消息处理链路中自动传递
*
* @author luna
* @date 2024/08/11
*/
@Slf4j
public class SipTransactionContext {
/**
* 线程本地存储原始请求事件(显式模式)
*/
private static final ThreadLocal<RequestEvent> REQUEST_EVENT_HOLDER = new ThreadLocal<>();
/**
* 线程本地存储完整事务信息(隐式模式)
*/
private static final ThreadLocal<SipTransactionInfo> TRANSACTION_INFO_HOLDER = new ThreadLocal<>();
/**
* 线程本地存储Call-ID(向后兼容)
*/
private static final ThreadLocal<String> CALL_ID_HOLDER = new ThreadLocal<>();
/**
* 线程本地存储事务类型标识
*/
private static final ThreadLocal<TransactionType> TRANSACTION_TYPE_HOLDER = new ThreadLocal<>();
/**
* SIP事务完整信息
* 包含事务匹配所需的所有关键信息
*/
@Data
public static class SipTransactionInfo {
/**
* Call-ID头部
*/
private String callId;
/**
* CSeq头部(序列号和方法)
*/
private Long cSeq;
/**
* CSeq方法
*/
private String method;
/**
* From头部
*/
private String fromHeader;
/**
* To头部
*/
private String toHeader;
/**
* From标签
*/
private String fromTag;
/**
* To标签
*/
private String toTag;
/**
* 从RequestEvent提取事务信息
*/
public static SipTransactionInfo fromRequestEvent(RequestEvent requestEvent) {
if (requestEvent == null) {
return null;
}
try {
Request request = requestEvent.getRequest();
SipTransactionInfo info = new SipTransactionInfo();
// 提取Call-ID
CallIdHeader callIdHeader = (CallIdHeader) request.getHeader(CallIdHeader.NAME);
if (callIdHeader != null) {
info.setCallId(callIdHeader.getCallId());
}
// 提取CSeq
CSeqHeader cSeqHeader = (CSeqHeader) request.getHeader(CSeqHeader.NAME);
if (cSeqHeader != null) {
info.setCSeq(cSeqHeader.getSeqNumber());
info.setMethod(cSeqHeader.getMethod());
}
// 提取From头部
FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME);
if (fromHeader != null) {
info.setFromHeader(fromHeader.toString());
info.setFromTag(fromHeader.getTag());
}
// 提取To头部
ToHeader toHeader = (ToHeader) request.getHeader(ToHeader.NAME);
if (toHeader != null) {
info.setToHeader(toHeader.toString());
info.setToTag(toHeader.getTag());
}
return info;
} catch (Exception e) {
log.warn("从RequestEvent提取事务信息失败", e);
return null;
}
}
@Override
public String toString() {
return String.format("SipTransactionInfo{callId='%s', cSeq=%d %s, from='%s', to='%s'}",
callId, cSeq, method, fromHeader, toHeader);
}
}
/**
* 事务类型枚举
*/
public enum TransactionType {
/**
* 显式事务:基于原始RequestEvent
*/
EXPLICIT,
/**
* 隐式事务:基于ThreadLocal传递的Call-ID
*/
IMPLICIT
}
// ==================== 显式模式方法 ====================
/**
* 设置原始请求事件(显式模式)
* 自动提取完整的事务信息
*
* @param requestEvent 原始请求事件
*/
public static void setRequestEvent(RequestEvent requestEvent) {
if (requestEvent != null) {
REQUEST_EVENT_HOLDER.set(requestEvent);
TRANSACTION_TYPE_HOLDER.set(TransactionType.EXPLICIT);
// 提取完整事务信息
SipTransactionInfo transactionInfo = SipTransactionInfo.fromRequestEvent(requestEvent);
if (transactionInfo != null) {
TRANSACTION_INFO_HOLDER.set(transactionInfo);
// 向后兼容:同时设置Call-ID
CALL_ID_HOLDER.set(transactionInfo.getCallId());
log.debug("设置SIP事务上下文(显式模式): {}", transactionInfo);
} else {
log.warn("无法从RequestEvent提取事务信息");
}
}
}
/**
* 获取原始请求事件
*
* @return 原始请求事件,如果不存在则返回null
*/
public static RequestEvent getRequestEvent() {
return REQUEST_EVENT_HOLDER.get();
}
// ==================== 隐式模式方法 ====================
/**
* 设置完整事务信息(隐式模式)
* 通常在AbstractSipListener中自动调用
*
* @param transactionInfo 完整事务信息
*/
public static void setTransactionInfo(SipTransactionInfo transactionInfo) {
if (transactionInfo != null) {
TRANSACTION_INFO_HOLDER.set(transactionInfo);
// 如果没有显式设置RequestEvent,则使用隐式模式
if (REQUEST_EVENT_HOLDER.get() == null) {
TRANSACTION_TYPE_HOLDER.set(TransactionType.IMPLICIT);
}
// 向后兼容:同时设置Call-ID
if (transactionInfo.getCallId() != null) {
CALL_ID_HOLDER.set(transactionInfo.getCallId());
}
log.debug("设置SIP事务上下文(隐式模式): {}", transactionInfo);
}
}
/**
* 设置Call-ID(隐式模式 - 向后兼容)
* 在消息处理器中自动调用,无需业务代码干预
*
* @param callId Call-ID
*/
public static void setCallId(String callId) {
if (callId != null && !callId.trim().isEmpty()) {
CALL_ID_HOLDER.set(callId.trim());
// 如果没有显式设置RequestEvent,则使用隐式模式
if (REQUEST_EVENT_HOLDER.get() == null) {
TRANSACTION_TYPE_HOLDER.set(TransactionType.IMPLICIT);
}
log.debug("设置SIP事务上下文(隐式Call-ID模式): callId={}", callId);
}
}
/**
* 获取当前线程的完整事务信息
* 优先级:显式模式的RequestEvent > 隐式模式的TransactionInfo
*
* @return 完整事务信息,如果不存在则返回null
*/
public static SipTransactionInfo getCurrentTransactionInfo() {
// 优先从显式模式获取
RequestEvent requestEvent = REQUEST_EVENT_HOLDER.get();
if (requestEvent != null) {
SipTransactionInfo info = SipTransactionInfo.fromRequestEvent(requestEvent);
if (info != null) {
log.debug("从显式模式获取事务信息: {}", info);
return info;
}
}
// 从隐式模式获取
SipTransactionInfo info = TRANSACTION_INFO_HOLDER.get();
if (info != null) {
log.debug("从隐式模式获取事务信息: {}", info);
}
return info;
}
/**
* 获取当前线程的Call-ID
* 优先级:显式模式的RequestEvent > 隐式模式的Call-ID
*
* @return Call-ID,如果不存在则返回null
*/
public static String getCurrentCallId() {
// 优先从显式模式获取
RequestEvent requestEvent = REQUEST_EVENT_HOLDER.get();
if (requestEvent != null) {
try {
String callId = requestEvent.getRequest().getHeader("Call-ID").toString();
log.debug("从显式模式获取Call-ID: {}", callId);
return callId;
} catch (Exception e) {
log.warn("从RequestEvent获取Call-ID失败", e);
}
}
// 从隐式模式获取
String callId = CALL_ID_HOLDER.get();
if (callId != null) {
log.debug("从隐式模式获取Call-ID: {}", callId);
}
return callId;
}
// ==================== 事务状态查询 ====================
/**
* 检查是否存在活跃的SIP事务上下文
*
* @return true如果存在活跃的事务上下文
*/
public static boolean hasActiveTransaction() {
return REQUEST_EVENT_HOLDER.get() != null || CALL_ID_HOLDER.get() != null;
}
/**
* 获取当前事务类型
*
* @return 事务类型,如果不存在则返回null
*/
public static TransactionType getCurrentTransactionType() {
return TRANSACTION_TYPE_HOLDER.get();
}
/**
* 检查是否为显式事务模式
*
* @return true如果为显式事务模式
*/
public static boolean isExplicitTransaction() {
return TransactionType.EXPLICIT.equals(TRANSACTION_TYPE_HOLDER.get());
}
/**
* 检查是否为隐式事务模式
*
* @return true如果为隐式事务模式
*/
public static boolean isImplicitTransaction() {
return TransactionType.IMPLICIT.equals(TRANSACTION_TYPE_HOLDER.get());
}
// ==================== 上下文管理 ====================
/**
* 清理当前线程的事务上下文
* 建议在处理完成后调用,避免内存泄漏
*/
public static void clear() {
String callId = getCurrentCallId();
TransactionType type = TRANSACTION_TYPE_HOLDER.get();
REQUEST_EVENT_HOLDER.remove();
TRANSACTION_INFO_HOLDER.remove();
CALL_ID_HOLDER.remove();
TRANSACTION_TYPE_HOLDER.remove();
log.debug("清理SIP事务上下文: callId={}, type={}", callId, type);
}
/**
* 复制事务上下文到新线程
* 用于异步处理时传递事务上下文
*
* @return 事务上下文快照
*/
public static TransactionSnapshot snapshot() {
RequestEvent requestEvent = REQUEST_EVENT_HOLDER.get();
String callId = CALL_ID_HOLDER.get();
TransactionType type = TRANSACTION_TYPE_HOLDER.get();
return new TransactionSnapshot(requestEvent, callId, type);
}
/**
* 从快照恢复事务上下文
*
* @param snapshot 事务上下文快照
*/
public static void restore(TransactionSnapshot snapshot) {
if (snapshot != null) {
if (snapshot.getRequestEvent() != null) {
REQUEST_EVENT_HOLDER.set(snapshot.getRequestEvent());
}
if (snapshot.getCallId() != null) {
CALL_ID_HOLDER.set(snapshot.getCallId());
}
if (snapshot.getType() != null) {
TRANSACTION_TYPE_HOLDER.set(snapshot.getType());
}
log.debug("恢复SIP事务上下文: callId={}, type={}", snapshot.getCallId(), snapshot.getType());
}
}
// ==================== 调试和诊断 ====================
/**
* 获取当前事务上下文的调试信息
*
* @return 调试信息字符串
*/
public static String getDebugInfo() {
RequestEvent requestEvent = REQUEST_EVENT_HOLDER.get();
String callId = CALL_ID_HOLDER.get();
TransactionType type = TRANSACTION_TYPE_HOLDER.get();
StringBuilder sb = new StringBuilder();
sb.append("SipTransactionContext{");
sb.append("thread=").append(Thread.currentThread().getName());
sb.append(", type=").append(type);
sb.append(", hasRequestEvent=").append(requestEvent != null);
sb.append(", callId='").append(callId != null ? callId : getCurrentCallId()).append("'");
sb.append("}");
return sb.toString();
}
/**
* 事务上下文快照,用于线程间传递
*/
public static class TransactionSnapshot {
private final RequestEvent requestEvent;
private final String callId;
private final TransactionType type;
public TransactionSnapshot(RequestEvent requestEvent, String callId, TransactionType type) {
this.requestEvent = requestEvent;
this.callId = callId;
this.type = type;
}
public RequestEvent getRequestEvent() {
return requestEvent;
}
public String getCallId() {
return callId;
}
public TransactionType getType() {
return type;
}
}
} | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
lunasaw/gb28181-proxy | https://github.com/lunasaw/gb28181-proxy/blob/540577abe2124425b68b6288de9e9fc341b1f1fc/sip-common/src/main/java/io/github/lunasaw/sip/common/enums/ContentTypeEnum.java | sip-common/src/main/java/io/github/lunasaw/sip/common/enums/ContentTypeEnum.java | package io.github.lunasaw.sip.common.enums;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.sip.header.ContentTypeHeader;
import io.github.lunasaw.sip.common.utils.SipRequestUtils;
import lombok.SneakyThrows;
/**
* 消息体类型
* @author luna
*/
public enum ContentTypeEnum {
/**
* xml
*/
APPLICATION_XML("Application", "MANSCDP+xml"),
/**
* sdp
*/
APPLICATION_SDP("APPLICATION", "SDP"),
/**
*
*/
APPLICATION_MAN_SRTSP("Application", "MANSRTSP"),
;
private static final Map<String, ContentTypeHeader> MAP = new ConcurrentHashMap<>();
private final String type;
private final String subtype;
ContentTypeEnum(String type, String subtype) {
this.type = type;
this.subtype = subtype;
}
public static ContentTypeEnum fromContentTypeHeader(ContentTypeHeader header) {
for (ContentTypeEnum contentType : values()) {
if (contentType.type.equals(header.getContentType())
&& contentType.subtype.equals(header.getContentSubType())) {
return contentType;
}
}
return null;
}
public static ContentTypeEnum fromString(String contentType) {
for (ContentTypeEnum contentTypeEnum : values()) {
if (contentTypeEnum.toString().equalsIgnoreCase(contentType)) {
return contentTypeEnum;
}
}
return null;
}
@SneakyThrows
public ContentTypeHeader getContentTypeHeader() {
String key = toString();
if (MAP.containsKey(key)) {
return MAP.get(key);
} else {
ContentTypeHeader contentTypeHeader = SipRequestUtils.createContentTypeHeader(type, subtype);
MAP.put(key, contentTypeHeader);
return contentTypeHeader;
}
}
@Override
public String toString() {
return type + "/" + subtype;
}
} | java | Apache-2.0 | 540577abe2124425b68b6288de9e9fc341b1f1fc | 2026-01-05T02:36:27.870323Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/collide/client/filetree/FileTreeContextMenuControllerTest.java | javatests/collide/client/filetree/FileTreeContextMenuControllerTest.java | // Copyright 2012 Google Inc. 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.
package collide.client.filetree;
import collide.client.common.CanRunApplication;
import collide.client.filetree.AppContextFileTreeController;
import collide.client.filetree.FileTreeContextMenuController;
import collide.client.filetree.FileTreeController;
import collide.client.filetree.FileTreeModel;
import collide.client.filetree.FileTreeNode;
import collide.client.filetree.FileTreeNodeDataAdapter;
import collide.client.filetree.FileTreeNodeRenderer;
import collide.client.filetree.FileTreeUiController;
import collide.client.treeview.Tree;
import collide.client.treeview.TreeNodeElement;
import collide.client.treeview.TreeNodeLabelRenamer;
import collide.client.util.Elements;
import com.google.collide.client.Resources;
import com.google.collide.client.code.debugging.DebuggingModel;
import com.google.collide.client.code.debugging.DebuggingModelController;
import com.google.collide.client.code.popup.EditorPopupController;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.history.Place;
import com.google.collide.client.history.PlaceNavigationEvent;
import com.google.collide.client.testing.CommunicationGwtTestCase;
import com.google.collide.client.testing.StubWorkspaceInfo;
import com.google.collide.client.workspace.MockOutgoingController;
import com.google.collide.client.workspace.TestUtils;
import com.google.collide.dto.DirInfo;
import com.google.collide.dto.FileInfo;
import com.google.collide.dto.GetWorkspace;
import com.google.collide.dto.GetWorkspaceResponse;
import com.google.collide.dto.TreeNodeInfo;
import com.google.collide.dto.WorkspaceInfo;
import com.google.collide.dto.client.DtoClientImpls.DirInfoImpl;
import com.google.collide.dto.client.DtoClientImpls.GetWorkspaceImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonStringMap;
import elemental.dom.Element;
import elemental.html.IFrameElement;
/**
*/
public class FileTreeContextMenuControllerTest extends CommunicationGwtTestCase {
private FileTreeContextMenuController controller;
private Tree<FileTreeNode> tree;
@Override
public String getModuleName() {
return TestUtils.BUILD_MODULE_NAME;
}
@Override
public void gwtSetUp() throws Exception {
super.gwtSetUp();
// Create our tree, with a model of a few dummy nodes.
FileTreeNodeDataAdapter dataAdapter = new FileTreeNodeDataAdapter();
FileTreeNodeRenderer nodeRenderer =
FileTreeNodeRenderer.create(context.getResources());
Tree.View<FileTreeNode> view = new Tree.View<FileTreeNode>(context.getResources());
Tree.Model<FileTreeNode> model =
new Tree.Model<FileTreeNode>(dataAdapter, nodeRenderer, context.getResources());
// An empty root directory.
DirInfoImpl mockDirInfo = DirInfoImpl.make();
mockDirInfo.setNodeType(TreeNodeInfo.DIR_TYPE);
JsoArray<FileInfo> files = JsoArray.create();
mockDirInfo.setFiles(files);
JsoArray<DirInfo> subdirs = JsoArray.create();
mockDirInfo.setSubDirectories(subdirs);
mockDirInfo.setName("");
mockDirInfo.setIsComplete(true);
FileTreeNode root = FileTreeNode.transform(mockDirInfo);
model.setRoot(root);
tree = new Tree<FileTreeNode>(view, model);
// Create all the other objects we need, or mocks for them...
Place place = new Place("mockPlace") {
@Override
public PlaceNavigationEvent<? extends Place> createNavigationEvent(
JsonStringMap<String> decodedState) {
return null;
}
};
FileTreeModel fileTreeModel = new FileTreeModel(new MockOutgoingController());
DebuggingModel debuggingModel = new DebuggingModel();
Editor editor = Editor.create(context);
EditorPopupController editorPopupController =
EditorPopupController.create(context.getResources(), editor);
DebuggingModelController<Resources> debuggingModelController = DebuggingModelController.create(
place, context.getResources(), debuggingModel, editor, editorPopupController, null);
JsoStringMap<String> templates = JsoStringMap.create();
FileTreeController<?> ctrl = new AppContextFileTreeController(context);
FileTreeUiController uiController = FileTreeUiController.create(place,
fileTreeModel,
tree,
ctrl ,
debuggingModelController);
TreeNodeLabelRenamer<FileTreeNode> nodeRenamer =
new TreeNodeLabelRenamer<FileTreeNode>(nodeRenderer, dataAdapter,
context.getResources().workspaceNavigationFileTreeNodeRendererCss());
// ...all by way of getting to create the thing we actually want:
controller = new FileTreeContextMenuController(place,
uiController,
fileTreeModel,
nodeRenamer,
ctrl,
debuggingModelController);
}
@Override
public void gwtTearDown() throws Exception {
super.gwtTearDown();
Element iframe =
Elements.getDocument().getElementById(FileTreeContextMenuController.DOWNLOAD_FRAME_ID);
if (iframe != null) {
iframe.removeFromParent();
}
}
public void testDownloadUnknownWorkspace() {
FileTreeNode data = null;
TreeNodeElement<FileTreeNode> parentTreeNode = tree.getNode(tree.getModel().getRoot());
controller.handleDownload(parentTreeNode, true);
Element iframe =
Elements.getDocument().getElementById(FileTreeContextMenuController.DOWNLOAD_FRAME_ID);
assertFalse("No iframe added", iframe == null);
String url = ((IFrameElement) iframe).getSrc();
// TODO: fix
// assertTrue("Bad url: " + url, url.contains("/workspace-" + MOCK_WORKSPACE_ID + ".zip?"));
}
public void testDownloadWorkspace() {
FileTreeNode data = null;
TreeNodeElement<FileTreeNode> parentTreeNode = tree.getNode(tree.getModel().getRoot());
expectMockWorkspaceInfo("Mock Workspace");
controller.handleDownload(parentTreeNode, true);
Element iframe =
Elements.getDocument().getElementById(FileTreeContextMenuController.DOWNLOAD_FRAME_ID);
assertFalse(iframe == null);
String url = ((IFrameElement) iframe).getSrc();
assertTrue("Bad url: " + url, url.contains("/Mock_Workspace.zip?rt=zip&"));
assertTrue("Bad url: " + url, url.endsWith("&file=/"));
iframe.removeFromParent();
controller.handleDownload(null, true);
iframe = Elements.getDocument().getElementById(FileTreeContextMenuController.DOWNLOAD_FRAME_ID);
assertFalse(iframe == null);
url = ((IFrameElement) iframe).getSrc();
assertTrue("Bad url: " + url, url.contains("/Mock_Workspace.zip?rt=zip&"));
assertTrue("Bad url: " + url, url.endsWith("&file=/"));
iframe.removeFromParent();
}
public void testBadCharacterWorkspace() {
FileTreeNode data = null;
TreeNodeElement<FileTreeNode> parentTreeNode = tree.getNode(tree.getModel().getRoot());
expectMockWorkspaceInfo("M o\tc/k:W\\o;r'k\"s&p?a#c%e");
controller.handleDownload(parentTreeNode, true);
Element iframe =
Elements.getDocument().getElementById(FileTreeContextMenuController.DOWNLOAD_FRAME_ID);
assertFalse(iframe == null);
String url = ((IFrameElement) iframe).getSrc();
assertTrue("Bad url: " + url, url.contains("/M_o_c_k_W_o_r_k_s%26p%3Fa%23c%25e.zip?"));
}
private GetWorkspace makeRequest() {
return GetWorkspaceImpl.make();
}
private void expectMockWorkspaceInfo(final String name) {
GetWorkspace request = makeRequest();
GetWorkspaceResponse response = new GetWorkspaceResponse() {
WorkspaceInfo info = StubWorkspaceInfo
.make()
.setName(name)
.setDescription("description of a workspace " + name)
.setParentId("mockParentWorkspaceId");
@Override
public WorkspaceInfo getWorkspace() {
return info;
}
@Override
public int getType() {
return 0;
}
};
// TODO: fix?
// context.getMockFrontendApi().getGetWorkspacesMockApi().expectAndReturn(request, response);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/collide/client/filetree/FileTreeNodeMoveControllerTest.java | javatests/collide/client/filetree/FileTreeNodeMoveControllerTest.java | // Copyright 2012 Google Inc. 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.
package collide.client.filetree;
import collide.client.filetree.FileTreeNode;
import collide.client.filetree.FileTreeNodeMoveController;
import com.google.collide.client.workspace.TestUtils;
import com.google.collide.dto.DirInfo;
import com.google.collide.dto.FileInfo;
import com.google.collide.dto.TreeNodeInfo;
import com.google.collide.dto.client.DtoClientImpls.DirInfoImpl;
import com.google.collide.dto.client.DtoClientImpls.FileInfoImpl;
import com.google.collide.json.client.JsoArray;
import com.google.gwt.junit.client.GWTTestCase;
/**
* Test cases for {@link FileTreeNodeMoveController}
*
*/
public class FileTreeNodeMoveControllerTest extends GWTTestCase {
@Override
public String getModuleName() {
return TestUtils.BUILD_MODULE_NAME;
}
private FileTreeNode createFileNode(String name) {
return FileInfoImpl.make().setName(name).setNodeType(TreeNodeInfo.FILE_TYPE).cast();
}
private FileTreeNode createFolderNode(String name) {
JsoArray<FileInfo> files = JsoArray.create();
JsoArray<DirInfo> subDirs = JsoArray.create();
return DirInfoImpl.make()
.setFiles(files)
.setSubDirectories(subDirs)
.setName(name)
.setNodeType(TreeNodeInfo.DIR_TYPE)
.cast();
}
public void testIsMoveAllowed() {
// d1
// --d2
// -----d3
// ---------f1.js
// ---------f2.js
// --d4
// -----f3.js
// d5
// --f4.js
// f5.js
FileTreeNode f1 = createFileNode("f1.js");
FileTreeNode f2 = createFileNode("f2.js");
FileTreeNode f3 = createFileNode("f3.js");
FileTreeNode f4 = createFileNode("f4.js");
FileTreeNode f5 = createFileNode("f5.js");
FileTreeNode d3 = createFolderNode("d3");
d3.addChild(f1);
d3.addChild(f2);
FileTreeNode d2 = createFolderNode("d2");
d2.addChild(d3);
FileTreeNode d4 = createFolderNode("d4");
d4.addChild(f3);
FileTreeNode d1 = createFolderNode("d1");
d1.addChild(d2);
d1.addChild(d4);
FileTreeNode d5 = createFolderNode("d5");
d5.addChild(f4);
FileTreeNode root = createFolderNode("");
root.addChild(d1);
root.addChild(d5);
root.addChild(f5);
FileTreeNodeMoveController moveController = new FileTreeNodeMoveController(null, null, null);
JsoArray<FileTreeNode> nodesToMove = JsoArray.create();
// Try to move "f1.js".
nodesToMove.add(f1);
moveController.setNodesToMove(nodesToMove);
assertFalse(moveController.isMoveAllowed(d3));
assertTrue(moveController.isMoveAllowed(d1));
assertTrue(moveController.isMoveAllowed(d2));
assertTrue(moveController.isMoveAllowed(d4));
assertTrue(moveController.isMoveAllowed(d5));
assertTrue(moveController.isMoveAllowed(root));
// Try to move "f5.js"
nodesToMove.clear();
nodesToMove.add(f5);
moveController.setNodesToMove(nodesToMove);
assertFalse(moveController.isMoveAllowed(root));
assertTrue(moveController.isMoveAllowed(d1));
assertTrue(moveController.isMoveAllowed(d2));
assertTrue(moveController.isMoveAllowed(d3));
assertTrue(moveController.isMoveAllowed(d4));
assertTrue(moveController.isMoveAllowed(d5));
// Try to move "d3"
nodesToMove.clear();
nodesToMove.add(d3);
moveController.setNodesToMove(nodesToMove);
assertFalse(moveController.isMoveAllowed(d3));
assertFalse(moveController.isMoveAllowed(d2));
assertTrue(moveController.isMoveAllowed(d1));
assertTrue(moveController.isMoveAllowed(d4));
assertTrue(moveController.isMoveAllowed(d5));
assertTrue(moveController.isMoveAllowed(root));
// Try to move "d2"
nodesToMove.clear();
nodesToMove.add(d2);
moveController.setNodesToMove(nodesToMove);
assertFalse(moveController.isMoveAllowed(d1));
assertFalse(moveController.isMoveAllowed(d2));
assertFalse(moveController.isMoveAllowed(d3));
assertTrue(moveController.isMoveAllowed(d4));
assertTrue(moveController.isMoveAllowed(d5));
assertTrue(moveController.isMoveAllowed(root));
// Try to move "d1"
nodesToMove.clear();
nodesToMove.add(d1);
moveController.setNodesToMove(nodesToMove);
assertFalse(moveController.isMoveAllowed(root));
assertFalse(moveController.isMoveAllowed(d1));
assertFalse(moveController.isMoveAllowed(d2));
assertFalse(moveController.isMoveAllowed(d3));
assertFalse(moveController.isMoveAllowed(d4));
assertTrue(moveController.isMoveAllowed(d5));
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/clientlibs/invalidation/DropRecoveringInvalidationControllerTest.java | javatests/com/google/collide/clientlibs/invalidation/DropRecoveringInvalidationControllerTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.clientlibs.invalidation;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.eq;
import com.google.collide.clientlibs.invalidation.InvalidationManager.Recoverer;
import com.google.collide.clientlibs.invalidation.InvalidationManager.Recoverer.Callback;
import com.google.collide.clientlibs.invalidation.InvalidationRegistrar.Listener;
import com.google.collide.clientlibs.invalidation.InvalidationRegistrar.Listener.AsyncProcessingHandle;
import com.google.collide.dto.RecoverFromDroppedTangoInvalidationResponse.RecoveredPayload;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.invalidations.InvalidationObjectId;
import com.google.collide.shared.invalidations.InvalidationObjectId.VersioningRequirement;
import com.google.collide.shared.invalidations.InvalidationUtils.InvalidationObjectPrefix;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.MockTimer;
import com.google.common.collect.Lists;
import junit.framework.TestCase;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.easymock.IMocksControl;
import java.util.List;
/**
* Tests for {@link DropRecoveringInvalidationController}.
*/
public class DropRecoveringInvalidationControllerTest extends TestCase {
private static class StubRecoveredPayload implements RecoveredPayload {
private final long version;
private final String payload;
public StubRecoveredPayload(long version, String payload) {
this.version = version;
this.payload = payload;
}
@Override
public String getPayload() {
return payload;
}
@Override
public int getPayloadVersion() {
return (int) version;
}
}
private static final InvalidationObjectId<?> obj = new InvalidationObjectId<Void>(
InvalidationObjectPrefix.FILE_TREE_MUTATION, "12345", VersioningRequirement.PAYLOADS);
/**
* The index corresponds to the version. Since there was never an invalidation to get to version
* 0, all invalidations will start at 1 for consistency.
*/
private static final List<String> PAYLOADS = Lists.newArrayList("a", "b", "c", "d", "e", "f", "g");
private IMocksControl strictControl;
private Listener listener;
private Recoverer recoverer;
private MockTimer.Factory timerFactory;
private DropRecoveringInvalidationControllerFactory controllerFactory;
public void testNormal() {
makeListenerExpectInvalidations(1, PAYLOADS.size());
strictControl.replay();
DropRecoveringInvalidationController controller =
controllerFactory.create(obj, listener, recoverer);
controller.setNextExpectedVersion(1);
for (int i = 1; i < PAYLOADS.size(); i++) {
controller.handleInvalidated(PAYLOADS.get(i), i, false);
}
timerFactory.tickToFireAllTimers();
strictControl.verify();
}
public void testNullPayloadNotCountedAsDropped() {
listener.onInvalidated(
eq(obj.getName()), eq(1L), eq((String) null), anyObject(AsyncProcessingHandle.class));
strictControl.replay();
DropRecoveringInvalidationController controller =
controllerFactory.create(obj, listener, recoverer);
controller.setNextExpectedVersion(1);
controller.handleInvalidated(null, 1, true);
timerFactory.tickToFireAllTimers();
strictControl.verify();
}
/**
* Test the object-bootstrap sequence: we subscribe to Tango and then do an XHR to fetch the full
* version of the object. Before we get the XHR response, we could have gotten invalidations.
*/
public void testBootstrapInOrder() {
strictControl.replay();
// Client instantiated/registered Tango listener and performs XHR
DropRecoveringInvalidationController controller =
controllerFactory.create(obj, listener, recoverer);
// While XHR is on the wire, we get a Tango invalidation
triggerInvalidated(controller, 1, 2, false);
// Ensure those invalidations didn't reach the listener
strictControl.verify();
strictControl.reset();
makeListenerExpectInvalidations(2, PAYLOADS.size());
strictControl.replay();
// We got XHR response, its payload start at version 2
controller.setNextExpectedVersion(2);
for (int i = 2; i < PAYLOADS.size(); i++) {
controller.handleInvalidated(PAYLOADS.get(i), i, false);
}
timerFactory.tickToFireAllTimers();
strictControl.verify();
}
/**
* Like {@link #testBootstrapInOrder()} except the there is overlap between the received payloads
* before we got the XHR response and the payloads in the XHR response.
*/
public void testBootstrapOverlap() {
strictControl.replay();
// Client instantiated/registered Tango listener and performs XHR
DropRecoveringInvalidationController controller =
controllerFactory.create(obj, listener, recoverer);
// While XHR is on the wire, we get a Tango invalidation
triggerInvalidated(controller, 1, 2, false);
// Ensure those invalidations didn't reach the listener
strictControl.verify();
strictControl.reset();
makeListenerExpectInvalidations(1, PAYLOADS.size());
strictControl.replay();
// We got XHR response, its payloads start at version 0
controller.setNextExpectedVersion(1);
for (int i = 2; i < PAYLOADS.size(); i++) {
controller.handleInvalidated(PAYLOADS.get(i), i, false);
}
timerFactory.tickToFireAllTimers();
strictControl.verify();
}
public void testSquelchedImmediatelyAfterBootstrap() {
makeRecovererExpectRecover(1, 3);
makeListenerExpectInvalidations(1, PAYLOADS.size());
strictControl.replay();
DropRecoveringInvalidationController controller =
controllerFactory.create(obj, listener, recoverer);
controller.setNextExpectedVersion(1);
// We were expecting v1 but got v2, recovery should kick off and get through v3 (defined above)
triggerInvalidated(controller, 2, PAYLOADS.size(), false);
timerFactory.tickToFireAllTimers();
strictControl.verify();
}
public void testSquelchedDuringOperation() {
makeListenerExpectInvalidations(1, 3);
makeRecovererExpectRecover(3, 3);
makeListenerExpectInvalidations(3, PAYLOADS.size());
strictControl.replay();
DropRecoveringInvalidationController controller =
controllerFactory.create(obj, listener, recoverer);
controller.setNextExpectedVersion(1);
// Invalidate v1 and v2, then v4 - end
triggerInvalidated(controller, 1, 3, false);
triggerInvalidated(controller, 4, PAYLOADS.size(), false);
timerFactory.tickToFireAllTimers();
strictControl.verify();
}
public void testDroppedPayloadsImmediatelyAfterBootstrap() {
makeRecovererExpectRecover(1, 1);
makeListenerExpectInvalidations(1, 2);
makeRecovererExpectRecover(2, 1);
makeListenerExpectInvalidations(2, PAYLOADS.size());
strictControl.replay();
DropRecoveringInvalidationController controller =
controllerFactory.create(obj, listener, recoverer);
controller.setNextExpectedVersion(1);
triggerInvalidated(controller, 1, 3, true);
triggerInvalidated(controller, 3, PAYLOADS.size(), false);
timerFactory.tickToFireAllTimers();
strictControl.verify();
}
public void testDroppedPayloadsDuringOperation() {
makeListenerExpectInvalidations(1, 4);
makeRecovererExpectRecover(4, 1);
makeListenerExpectInvalidations(4, 5);
makeRecovererExpectRecover(5, 1);
makeListenerExpectInvalidations(5, PAYLOADS.size());
strictControl.replay();
DropRecoveringInvalidationController controller =
controllerFactory.create(obj, listener, recoverer);
controller.setNextExpectedVersion(1);
triggerInvalidated(controller, 1, 4, false);
triggerInvalidated(controller, 4, 6, true);
triggerInvalidated(controller, 6, PAYLOADS.size(), false);
timerFactory.tickToFireAllTimers();
strictControl.verify();
}
public void testOutageOfAllDroppedPayloads() {
for (int i = 1; i < PAYLOADS.size(); i++) {
makeRecovererExpectRecover(i, 1);
makeListenerExpectInvalidations(i, i + 1);
}
strictControl.replay();
DropRecoveringInvalidationController controller =
controllerFactory.create(obj, listener, recoverer);
controller.setNextExpectedVersion(1);
triggerInvalidated(controller, 1, PAYLOADS.size(), true);
timerFactory.tickToFireAllTimers();
strictControl.verify();
}
@Override
protected void setUp() throws Exception {
strictControl = EasyMock.createStrictControl();
recoverer = strictControl.createMock(Recoverer.class);
listener = strictControl.createMock(Listener.class);
timerFactory = new MockTimer.Factory();
controllerFactory = new DropRecoveringInvalidationControllerFactory(
new InvalidationLogger(false, false), timerFactory);
}
/**
* @param end exclusive
*/
private void makeListenerExpectInvalidations(int begin, int end) {
for (int i = begin; i < end; i++) {
listener.onInvalidated(eq(obj.getName()), eq((long) i), eq(PAYLOADS.get(i)),
anyObject(AsyncProcessingHandle.class));
}
}
/**
* @param end exclusive
* @param dropPayloads TODO:
*/
private void triggerInvalidated(
DropRecoveringInvalidationController controller, int begin, int end, boolean dropPayloads) {
for (int i = begin; i < end; i++) {
controller.handleInvalidated(dropPayloads ? null : PAYLOADS.get(i), i, !dropPayloads);
}
}
private void makeRecovererExpectRecover(final int nextExpectedVersion, final int payloadCount) {
recoverer.recoverPayloads(
EasyMock.eq(obj), EasyMock.eq(nextExpectedVersion - 1), EasyMock.anyObject(Callback.class));
EasyMock.expectLastCall().andAnswer(new IAnswer<Void>() {
@Override
public Void answer() throws Throwable {
Callback callback = (Callback) EasyMock.getCurrentArguments()[2];
JsonArray<RecoveredPayload> recoveredPayloads = JsonCollections.createArray();
for (int i = nextExpectedVersion; i < nextExpectedVersion + payloadCount; i++) {
recoveredPayloads.add(new StubRecoveredPayload(i, PAYLOADS.get(i)));
}
callback.onPayloadsRecovered(recoveredPayloads, nextExpectedVersion);
return null;
}
});
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/clientlibs/invalidation/MockInvalidationRegistrar.java | javatests/com/google/collide/clientlibs/invalidation/MockInvalidationRegistrar.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.clientlibs.invalidation;
import com.google.collide.clientlibs.invalidation.InvalidationRegistrar;
import com.google.collide.shared.invalidations.InvalidationObjectId;
/**
* Mock version of {@link InvalidationRegistrar} that does not fire any
* invalidations
*/
public class MockInvalidationRegistrar implements InvalidationRegistrar {
@Override
public RemovableHandle register(InvalidationObjectId<?> objectId, Listener eventListener) {
return new RemovableHandle() {
@Override
public void remove() {
}
@Override
public void initializeRecoverer(long nextExpectedVersion) {
}
};
}
@Override
public void unregister(InvalidationObjectId<?> objectId) {
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/clientlibs/navigation/DefaultUrlSerializerTests.java | javatests/com/google/collide/clientlibs/navigation/DefaultUrlSerializerTests.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.clientlibs.navigation;
import junit.framework.TestCase;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap.IterationCallback;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.base.Equivalence;
/**
*/
public class DefaultUrlSerializerTests extends TestCase {
/**
* A class which simplifies building/asserting a url.
*/
private class UrlBuilder {
private final StringBuilder url = new StringBuilder();
public UrlBuilder place(String placeName) {
url.append(UrlSerializer.PATH_SEPARATOR);
url.append(urlEncoder.encode(placeName));
return this;
}
public UrlBuilder value(String key, String value) {
if (value == null) {
return this;
}
String encodedKey = urlEncoder.encode(key);
String encodedValue = urlEncoder.encode(value);
url.append(UrlSerializer.PATH_SEPARATOR);
url.append(encodedKey).append(DefaultUrlSerializer.KEY_VALUE_SEPARATOR).append(encodedValue);
return this;
}
public UrlBuilder token(NavigationToken token) {
place(token.getPlaceName());
token.getBookmarkableState().iterate(new IterationCallback<String>() {
@Override
public void onIteration(String key, String value) {
value(key, value);
}
});
return this;
}
public UrlBuilder tokens(JsonArray<NavigationToken> navTokens) {
for (int i = 0; i < navTokens.size(); i++) {
token(navTokens.get(i));
}
return this;
}
public void assertMatch(String resultUrl) {
TestCase.assertEquals("Url did not match", url.toString(), resultUrl);
}
}
private static final String HOME_PLACE = "HOME";
private static final String LEAF_PLACE = "LEAF";
private static final String DETAIL_PLACE = "DETAIL";
private static final String EMPTY_PLACE = "EMPTY";
/** Identifies the home place, has no properties */
private static final NavigationToken HOME_TOKEN = new NavigationTokenImpl(HOME_PLACE);
/** Identifies a leaf place, has only a single property */
private static final NavigationToken LEAF_TOKEN = new NavigationTokenImpl(LEAF_PLACE);
/** Identifies a detail place, has three properties */
private static final NavigationToken DETAIL_TOKEN = new NavigationTokenImpl(DETAIL_PLACE);
/** Identifies the EMPTY place, has some weird properties null/empty string */
private static final NavigationToken EMPTY_TOKEN = new NavigationTokenImpl(EMPTY_PLACE);
private static final UrlComponentEncoder urlEncoder = new StubUrlEncoder();
private static final Equivalence<NavigationToken> NAVIGATION_EQUIVALENCE =
new Equivalence<NavigationToken>() {
@Override
public boolean doEquivalent(NavigationToken a, NavigationToken b) {
return a.getPlaceName().equals(b.getPlaceName()) && JsonCollections.equals(
a.getBookmarkableState(), b.getBookmarkableState());
}
@Override
public int doHash(NavigationToken t) {
return t.getPlaceName().hashCode() ^ t.getBookmarkableState().hashCode();
}
};
static {
LEAF_TOKEN.getBookmarkableState().put("one", "one");
DETAIL_TOKEN.getBookmarkableState().put("one", "one");
DETAIL_TOKEN.getBookmarkableState().put("two", "two");
DETAIL_TOKEN.getBookmarkableState().put("three", "three");
EMPTY_TOKEN.getBookmarkableState().put("one", null);
EMPTY_TOKEN.getBookmarkableState().put("two", "");
// This really tests the encoder more than anything...
EMPTY_TOKEN.getBookmarkableState().put("three", DefaultUrlSerializer.PATH_SEPARATOR);
EMPTY_TOKEN.getBookmarkableState()
.put("four", String.valueOf(DefaultUrlSerializer.KEY_VALUE_SEPARATOR));
}
private UrlSerializer serializer;
@Override
public void setUp() {
serializer = new DefaultUrlSerializer(urlEncoder);
}
public void testHome() {
assertTokens(JsonCollections.createArray(HOME_TOKEN));
assertTokens(JsonCollections.createArray(HOME_TOKEN, HOME_TOKEN, HOME_TOKEN));
}
public void testLeaf() {
assertTokens(JsonCollections.createArray(LEAF_TOKEN));
assertTokens(JsonCollections.createArray(HOME_TOKEN, LEAF_TOKEN, LEAF_TOKEN));
assertTokens(JsonCollections.createArray(HOME_TOKEN, LEAF_TOKEN, HOME_TOKEN));
}
public void testDetail() {
assertTokens(JsonCollections.createArray(DETAIL_TOKEN));
assertTokens(JsonCollections.createArray(HOME_TOKEN, LEAF_TOKEN, DETAIL_TOKEN));
assertTokens(JsonCollections.createArray(DETAIL_TOKEN, HOME_TOKEN, LEAF_TOKEN, DETAIL_TOKEN));
}
public void testWeird() {
NavigationToken modifiedEmptyToken = new NavigationTokenImpl(EMPTY_PLACE);
modifiedEmptyToken.getBookmarkableState().putAll(EMPTY_TOKEN.getBookmarkableState());
modifiedEmptyToken.getBookmarkableState().remove("one");
// We have to be explit here since we are ignoring null
JsonArray<NavigationToken> tokens = JsonCollections.createArray(EMPTY_TOKEN);
String url = serializer.serialize(tokens);
new UrlBuilder().token(modifiedEmptyToken).assertMatch(url);
assertEquals(JsonCollections.createArray(modifiedEmptyToken), serializer.deserialize(url));
tokens = JsonCollections.createArray(DETAIL_TOKEN, EMPTY_TOKEN, LEAF_TOKEN);
url = serializer.serialize(tokens);
new UrlBuilder().token(DETAIL_TOKEN)
.token(modifiedEmptyToken).token(LEAF_TOKEN).assertMatch(url);
assertEquals(JsonCollections.createArray(DETAIL_TOKEN, modifiedEmptyToken, LEAF_TOKEN),
serializer.deserialize(url));
}
private void assertTokens(JsonArray<NavigationToken> tokens) {
String url = serializer.serialize(tokens);
new UrlBuilder().tokens(tokens).assertMatch(url);
assertEquals(tokens, serializer.deserialize(url));
}
private void assertEquals(
JsonArray<NavigationToken> expected, JsonArray<NavigationToken> actual) {
boolean isEqual = JsonCollections.equals(expected, actual, NAVIGATION_EQUIVALENCE);
if (!isEqual) {
failNotEquals("Deserialized URL was not the same", expected, actual);
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/clientlibs/navigation/StubUrlEncoder.java | javatests/com/google/collide/clientlibs/navigation/StubUrlEncoder.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.clientlibs.navigation;
/**
* A url encoder which encodes special characters for testing.
*/
public class StubUrlEncoder implements UrlComponentEncoder {
@Override
public String decode(String text) {
return text.replaceAll("__E__", String.valueOf(DefaultUrlSerializer.KEY_VALUE_SEPARATOR))
.replaceAll("__S__", UrlSerializer.PATH_SEPARATOR);
}
@Override
public String encode(String text) {
return text.replaceAll(String.valueOf(DefaultUrlSerializer.KEY_VALUE_SEPARATOR), "__E__")
.replaceAll(UrlSerializer.PATH_SEPARATOR, "__S__");
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/json/server/JsonListAdapterTests.java | javatests/com/google/collide/json/server/JsonListAdapterTests.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.json.server;
import com.google.collide.json.shared.JsonArray;
import junit.framework.TestCase;
import java.util.ArrayList;
/**
* Tests a JSON List adapter used by JsonArray
*/
public class JsonListAdapterTests extends TestCase {
private static <T> JsonArray<T> create() {
return new JsonArrayListAdapter<T>(new ArrayList<T>());
}
public void testOutOfBounds() {
JsonArray<Integer> numbers = create();
numbers.add(0);
try {
numbers.set(2, 2);
} catch (IndexOutOfBoundsException ex) {
// We expect this.
return;
}
fail("IndexOutOfBoundsException didn't occur");
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/json/client/JsoArrayTest.java | javatests/com/google/collide/json/client/JsoArrayTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.json.client;
import com.google.collide.shared.util.JsonCollections;
import com.google.gwt.junit.client.GWTTestCase;
import java.util.Comparator;
/**
* Tests for JsoArray.
*
*/
public class JsoArrayTest extends GWTTestCase {
@Override
public String getModuleName() {
return "com.google.collide.json.client.JsonClientTestModule";
}
public void testAddAllMissingDisjoint() {
JsoArray<String> a = JsoArray.create();
a.add("a1");
a.add("a2");
JsoArray<String> b = JsoArray.create();
b.add("b1");
b.add("b2");
JsonCollections.addAllMissing(a, b);
assertEquals(4, a.size());
assertEquals(2, b.size());
assertEquals("a1,a2,b1,b2", a.join(","));
}
public void testAddAllMissingIntersecting() {
JsoArray<String> a = JsoArray.create();
a.add("a1");
a.add("a2");
JsoArray<String> b = JsoArray.create();
b.add("a1");
b.add("b2");
JsonCollections.addAllMissing(a, b);
assertEquals(3, a.size());
assertEquals("a1,a2,b2", a.join(","));
}
public void testAddAllMissingDuplicates() {
JsoArray<String> a = JsoArray.create();
a.add("a1");
a.add("a2");
a.add("a1");
JsoArray<String> b = JsoArray.create();
b.add("b1");
b.add("b2");
b.add("b1");
JsonCollections.addAllMissing(a, b);
assertEquals(6, a.size());
assertEquals("a1,a2,a1,b1,b2,b1", a.join(","));
}
public void testAddAllMissingEmpty() {
JsoArray<String> a = JsoArray.create();
a.add("a1");
JsonCollections.addAllMissing(a, JsoArray.<String>create());
assertEquals(1, a.size());
assertEquals("a1", a.get(0));
}
public void testAddAllMissingNull() {
JsoArray<String> a = JsoArray.create();
a.add("a1");
JsonCollections.addAllMissing(a, null);
assertEquals(1, a.size());
assertEquals("a1", a.get(0));
}
public void testAddAllMissingSelfToSelf() {
JsoArray<String> a = JsoArray.create();
a.add("a1");
a.add("a2");
JsonCollections.addAllMissing(a, a);
assertEquals(2, a.size());
assertEquals("a1,a2", a.join(","));
}
public void testEqualsBothNull() {
assertTrue(JsonCollections.equals((JsoArray<?>)null, null));
}
public void testEqualsOneNull() {
JsoArray<String> a = JsoArray.create();
a.add("a0");
a.add("a1");
assertFalse(JsonCollections.equals(a, null));
assertFalse(JsonCollections.equals(null, a));
}
public void testEqualsDifferentSize() {
JsoArray<String> aSmall = JsoArray.create();
aSmall.add("a0");
aSmall.add("a1");
JsoArray<String> aLarge = JsoArray.create();
aLarge.add("a0");
assertFalse(JsonCollections.equals(aSmall, aLarge));
}
public void testEquals() {
JsoArray<String> a0 = JsoArray.create();
a0.add("a0");
a0.add("a1");
JsoArray<String> a1 = JsoArray.create();
a1.add("a0");
a1.add("a1");
assertTrue(JsonCollections.equals(a0, a0));
assertTrue(JsonCollections.equals(a0, a1));
}
public void testNotEquals() {
JsoArray<String> a = JsoArray.create();
a.add("a0");
a.add("a1");
JsoArray<String> b = JsoArray.create();
b.add("a0");
b.add("b1");
assertFalse(JsonCollections.equals(a, b));
}
public void testSortWithComparator() {
JsoArray<String> a = JsoArray.create();
a.add("b");
a.add("a");
a.add("c");
assertArray(a, "b", "a", "c");
a.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
assertArray(a, "a", "b", "c");
a.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
assertArray(a, "c", "b", "a");
}
public void testReverse() {
JsoArray<String> a = JsoArray.from("a", "b", "c");
a.reverse();
assertArray(a, "c", "b", "a");
}
public void testOutOfBounds() {
JsoArray<Integer> numbers = JsoArray.from(0);
try {
numbers.set(2, 2);
} catch (IndexOutOfBoundsException ex) {
// We expect this.
return;
}
fail("IndexOutOfBoundsException didn't occur");
}
/**
* Assert that an array contains exactly the expected values, in order.
*
* @param <T> the data type of the array
* @param actual the actual array to check
* @param expected the expected values, in order
*/
private <T> void assertArray(JsoArray<T> actual, T... expected) {
// Check the size.
int size = expected.length;
assertEquals("Size mismatch", size, actual.size());
// Check the values.
for (int i = 0; i < size; i++) {
assertEquals(expected[i], actual.get(i));
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/json/client/JsoStringMapTest.java | javatests/com/google/collide/json/client/JsoStringMapTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.json.client;
import com.google.gwt.junit.client.GWTTestCase;
/**
* Test cases for {@link JsoStringMap}.
*/
public class JsoStringMapTest extends GWTTestCase {
private static final String[] TEST_KEYS = new String[]{
"something",
"",
"__defineGetter",
"__defineSetter__",
"__lookupGetter__",
"__lookupSetter__",
"constructor",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"toLocaleString",
"toString",
"valueOf",
//"__proto__"
};
private static final class Foo {
}
@Override
public String getModuleName() {
return "com.google.collide.json.client.JsonClientTestModule";
}
public void testEmpty() {
JsoStringMap<Foo> map = JsoStringMap.create();
assertTrue("emptiness", map.isEmpty());
JsoArray<String> keys = map.getKeys();
assertEquals("key list emptiness", 0, keys.size());
}
public void testIsEmpty() {
for (int i = 0, size = TEST_KEYS.length; i < size; i++) {
String key = TEST_KEYS[i];
JsoStringMap<Foo> map = JsoStringMap.create();
map.put(key, new Foo());
assertFalse("isEmpty with '" + key + "'", map.isEmpty());
}
}
public void testGetFromEmpty() {
for (int i = 0, size = TEST_KEYS.length; i < size; i++) {
String key = TEST_KEYS[i];
JsoStringMap<Foo> map = JsoStringMap.create();
Foo foo = map.get(key);
assertNull(".get('" + key + "') result", foo);
}
}
public void testDeleteFromEmpty() {
for (int i = 0, size = TEST_KEYS.length; i < size; i++) {
String key = TEST_KEYS[i];
JsoStringMap<Foo> map = JsoStringMap.create();
Foo foo = map.remove(key);
assertNull(".remove('" + key + "') result", foo);
}
}
public void testAddAndDeleteFromEmpty() {
for (int i = 0, size = TEST_KEYS.length; i < size; i++) {
String key = TEST_KEYS[i];
JsoStringMap<Foo> map = JsoStringMap.create();
Foo foo = new Foo();
map.put(key, foo);
Foo getFoo = map.get(key);
assertTrue(".get('" + key + "') result", foo == getFoo);
Foo deletedFoo = map.remove(key);
assertTrue(".remove('" + key + "') result", foo == deletedFoo);
}
}
public void testGetKeys() {
JsoStringMap<Foo> map = JsoStringMap.create();
Foo foo = new Foo();
for (int i = 0, size = TEST_KEYS.length; i < size; i++) {
map.put(TEST_KEYS[i], foo);
}
JsoArray<String> keys = map.getKeys();
assertEquals("number of keys", TEST_KEYS.length, keys.size());
for (int i = 0, size = TEST_KEYS.length; i < size; i++) {
String key = TEST_KEYS[i];
assertTrue("has key('" + key + "')", keys.contains(key));
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/json/client/JsoStringSetTest.java | javatests/com/google/collide/json/client/JsoStringSetTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.json.client;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringSet;
import com.google.gwt.junit.client.GWTTestCase;
/**
* Tests for {@link JsoStringSet}.
*/
public class JsoStringSetTest extends GWTTestCase {
@Override
public String getModuleName() {
return "com.google.collide.json.client.JsonClientTestModule";
}
public void testEmptySet() {
JsoStringSet set = JsoStringSet.create();
assertEquals(0, set.getKeys().size());
assertTrue(set.isEmpty());
}
public void testGetKeys() {
doTest(
JsoArray.from("a", "b", "c"), // Input data.
JsoArray.from("a", "b", "c"), // Expected.
JsoArray.from("d", "aa", "b0") // Not expected.
);
}
public void testDuplicatedKeys() {
doTest(
JsoArray.from("a", "b", "c", "b", "c", "a", "c", "a", "b"),
JsoArray.from("a", "b", "c"),
JsoArray.from("d", "aa", "b0")
);
}
public void testEmptyKey() {
doTestSingleKey("");
}
public void testProtoKey() {
doTestSingleKey("__proto__");
}
private void doTestSingleKey(String key) {
JsoStringSet set = JsoStringSet.create();
assertFalse(set.contains(key));
doTest(
JsoArray.from(key),
JsoArray.from(key),
JsoArray.from("d", "aa", "b0")
);
}
public void testAddAll() {
JsoStringSet set = createSet(JsoArray.from("a", "b", "c"));
JsonArray<String> oldKeys = set.getKeys();
JsonArray<String> newKeys = JsoArray.from("a", "x", "y", "x");
set.addAll(newKeys);
assertEquals("Size", 5, set.getKeys().size());
assertContainsAll(set, oldKeys);
assertContainsAll(set, newKeys);
}
private void doTest(JsoArray<String> inputKeys, final JsoArray<String> expectedKeys,
final JsoArray<String> notExpectedKeys) {
JsoStringSet set = createSet(inputKeys);
assertContainsAll(set, inputKeys);
assertContainsAll(set, expectedKeys);
if (inputKeys.size() == 0) {
assertTrue(set.isEmpty());
} else {
assertFalse(set.isEmpty());
}
JsonArray<String> keys = set.getKeys();
assertEquals(expectedKeys.size(), keys.size());
for (int i = 0, n = keys.size(); i < n; ++i) {
assertEquals(expectedKeys.get(i), keys.get(i));
}
for (int i = 0, n = notExpectedKeys.size(); i < n; ++i) {
assertFalse(set.contains(notExpectedKeys.get(i)));
}
set.iterate(new JsonStringSet.IterationCallback() {
@Override
public void onIteration(String key) {
assertTrue(expectedKeys.contains(key));
assertFalse(notExpectedKeys.contains(key));
}
});
}
private JsoStringSet createSet(JsoArray<String> keys) {
JsoStringSet set = JsoStringSet.create();
for (int i = 0, n = keys.size(); i < n; ++i) {
set.add(keys.get(i));
}
return set;
}
private void assertContainsAll(JsoStringSet set, JsonArray<String> keys) {
for (int i = 0, n = keys.size(); i < n; ++i) {
assertTrue(set.contains(keys.get(i)));
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/json/client/JsoTest.java | javatests/com/google/collide/json/client/JsoTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.json.client;
import com.google.gwt.junit.client.GWTTestCase;
/**
* Test cases for {@link Jso}.
*/
public class JsoTest extends GWTTestCase {
private static final String[] TEST_KEYS = new String[]{
"something",
"",
"__defineGetter",
"__defineSetter__",
"__lookupGetter__",
"__lookupSetter__",
"constructor",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"toLocaleString",
"toString",
"valueOf",
//"__proto__"
};
private static final class Foo {
}
@Override
public String getModuleName() {
return "com.google.collide.json.client.JsonClientTestModule";
}
public void testEmpty() {
Jso jso = Jso.create();
assertTrue("emptiness", jso.isEmpty());
JsoArray<String> keys = jso.getKeys();
assertEquals("key list emptiness", 0, keys.size());
}
public void testIsEmpty() {
for (int i = 0, size = TEST_KEYS.length; i < size; i++) {
String key = TEST_KEYS[i];
Jso jso = Jso.create();
jso.addField(key, new Foo());
assertFalse("isEmpty with '" + key + "'", jso.isEmpty());
}
}
public void testGetKeys() {
Jso jso = Jso.create();
Foo foo = new Foo();
for (int i = 0, size = TEST_KEYS.length; i < size; i++) {
jso.addField(TEST_KEYS[i], foo);
}
JsoArray<String> keys = jso.getKeys();
assertEquals("number of keys", TEST_KEYS.length, keys.size());
for (int i = 0, size = TEST_KEYS.length; i < size; i++) {
String key = TEST_KEYS[i];
assertTrue("has key('" + key + "')", keys.contains(key));
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/codemirror2/TokenUtilTest.java | javatests/com/google/collide/codemirror2/TokenUtilTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.codemirror2;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.Pair;
import com.google.collide.shared.util.JsonCollections;
import org.junit.Before;
import org.junit.Test;
/**
* JUnit4 test for {@link TokenUtil}.
*/
public class TokenUtilTest {
private JsonArray<Pair<Integer, String>> modes;
@Before
public void setUp() {
JsonArray<Token> tokens = JsonCollections.createArray();
tokens.add(new Token("html", null, "hhhhhhhh"));
tokens.add(new Token("css", null, "ccc"));
tokens.add(new Token("css", null, "CC"));
tokens.add(new Token("javascript", null, "jjjjj"));
tokens.add(new Token("html", null, "h"));
modes = TokenUtil.buildModes("#", tokens);
}
@Test
public void findModeForColumn() {
assertThrows("Column should be >= 0 but was -1", -1);
// Let the mode at column = 0 be the mode of the first tag.
// This makes sense because visually new line is sufficiently separate
// from the previous line so that whatever is the mode of the first tag
// on this line determines the mode of the first column.
assertEquals("html", TokenUtil.findModeForColumn("html", modes, 0));
assertEquals("html", TokenUtil.findModeForColumn("html", modes, 1));
assertEquals("html", TokenUtil.findModeForColumn("html", modes, 8));
assertEquals("css", TokenUtil.findModeForColumn("html", modes, 9));
assertEquals("css", TokenUtil.findModeForColumn("html", modes, 10));
assertEquals("css", TokenUtil.findModeForColumn("html", modes, 11));
assertEquals("css", TokenUtil.findModeForColumn("html", modes, 12));
assertEquals("css", TokenUtil.findModeForColumn("html", modes, 13));
assertEquals("javascript", TokenUtil.findModeForColumn("html", modes, 14));
assertEquals("javascript", TokenUtil.findModeForColumn("html", modes, 16));
assertEquals("html", TokenUtil.findModeForColumn("html", modes, 19));
assertEquals("html", TokenUtil.findModeForColumn("html", modes, 100));
assertEquals("html", TokenUtil.findModeForColumn("html",
JsonCollections.<Pair<Integer, String>>createArray(), 0));
assertEquals("html", TokenUtil.findModeForColumn("html",
JsonCollections.<Pair<Integer, String>>createArray(), 1));
}
@Test
public void buildModes() {
assertEquals(4, modes.size());
assertEquals(0, modes.get(0).first.intValue());
assertEquals("html", modes.get(0).second);
assertEquals(8, modes.get(1).first.intValue());
assertEquals("css", modes.get(1).second);
assertEquals(13, modes.get(2).first.intValue());
assertEquals("javascript", modes.get(2).second);
assertEquals(18, modes.get(3).first.intValue());
assertEquals("html", modes.get(3).second);
assertTrue(TokenUtil.buildModes("html", JsonCollections.<Token>createArray()).isEmpty());
}
@Test
public void addPlaceholders() {
JsonStringMap<JsonArray<Token>> splitTokenMap = JsonCollections.<JsonArray<Token>>createMap();
splitTokenMap.put("a", JsonCollections.<Token>createArray());
splitTokenMap.put("b", JsonCollections.<Token>createArray());
splitTokenMap.put("c", JsonCollections.<Token>createArray());
TokenUtil.addPlaceholders("c", splitTokenMap, 4);
assertEquals(3, splitTokenMap.size());
assertEquals(1, splitTokenMap.get("a").size());
Token tokenA = splitTokenMap.get("a").get(0);
assertEquals(TokenType.WHITESPACE, tokenA.getType());
assertEquals("a", tokenA.getMode());
assertEquals(" ", tokenA.getValue());
assertEquals(1, splitTokenMap.get("b").size());
Token tokenB = splitTokenMap.get("b").get(0);
assertEquals(TokenType.WHITESPACE, tokenB.getType());
assertEquals("b", tokenB.getMode());
assertEquals(" ", tokenB.getValue());
assertEquals(0, splitTokenMap.get("c").size());
}
private void assertThrows(String expectedMessage, int column) {
try {
TokenUtil.findModeForColumn("html", modes, column);
fail("Expected to throw an exception");
} catch (IllegalArgumentException e) {
// Expected exception
assertEquals(expectedMessage, e.getMessage());
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/dtogen/definitions/ComplicatedDto.java | javatests/com/google/collide/dtogen/definitions/ComplicatedDto.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.dtogen.definitions;
import com.google.collide.dtogen.shared.ClientToServerDto;
import com.google.collide.dtogen.shared.RoutingType;
import com.google.collide.dtogen.shared.ServerToClientDto;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
/**
* DTO for testing that the DTO generator correctly generates client and server
* implementations for object graphs (nested arrays, and maps).
*
*/
@RoutingType(type = ComplicatedDto.TYPE)
public interface ComplicatedDto extends ServerToClientDto, ClientToServerDto {
public static final int TYPE = 12346;
public enum SimpleEnum {
ONE, TWO, THREE
}
JsonArray<String> getFooStrings();
int getIntId();
SimpleEnum getSimpleEnum();
JsonStringMap<SimpleDto> getMap();
JsonArray<SimpleDto> getSimpleDtos();
JsonArray<JsonStringMap<JsonArray<JsonStringMap<JsonStringMap<JsonArray<SimpleDto>>>>>>
getNightmare();
JsonArray<JsonArray<SimpleEnum>> getArrayOfArrayOfEnum();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/dtogen/definitions/SimpleDtoSubType.java | javatests/com/google/collide/dtogen/definitions/SimpleDtoSubType.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.dtogen.definitions;
import com.google.collide.dtogen.shared.RoutingType;
@RoutingType(type = 12343)
public interface SimpleDtoSubType extends SimpleDto {
String getAnotherField();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/dtogen/definitions/NotRoutable.java | javatests/com/google/collide/dtogen/definitions/NotRoutable.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.dtogen.definitions;
public interface NotRoutable {
String getSomeField();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/dtogen/definitions/SimpleDto.java | javatests/com/google/collide/dtogen/definitions/SimpleDto.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.dtogen.definitions;
import com.google.collide.dtogen.shared.ClientToServerDto;
import com.google.collide.dtogen.shared.RoutingType;
import com.google.collide.dtogen.shared.ServerToClientDto;
@RoutingType(type = SimpleDto.TYPE)
public interface SimpleDto extends ServerToClientDto, ClientToServerDto {
public static final int TYPE = 12345;
String getName();
int getNumber();
int iDontStartWithGet();
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/dtogen/server/ServerImplTest.java | javatests/com/google/collide/dtogen/server/ServerImplTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.dtogen.server;
import com.google.collide.dtogen.definitions.ComplicatedDto;
import com.google.collide.dtogen.definitions.ComplicatedDto.SimpleEnum;
import com.google.collide.dtogen.definitions.NotRoutable;
import com.google.collide.dtogen.definitions.SimpleDto;
import com.google.collide.dtogen.server.TestDtoServerImpls.ComplicatedDtoImpl;
import com.google.collide.dtogen.server.TestDtoServerImpls.NotRoutableImpl;
import com.google.collide.dtogen.server.TestDtoServerImpls.SimpleDtoImpl;
import com.google.collide.dtogen.server.TestDtoServerImpls.SimpleDtoSubTypeImpl;
import com.google.collide.dtogen.shared.ServerToClientDto;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import junit.framework.TestCase;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Tests that the interfaces specified in com.google.gwt.dto.definitions have
* corresponding generated Server impls.
*/
public class ServerImplTest extends TestCase {
public void testComplicatedDtoImpl() {
final String fooString = "Something";
final int intId = 1;
ComplicatedDtoImpl dtoImpl = ComplicatedDtoImpl.make();
dtoImpl.setIntId(intId);
dtoImpl.setSimpleEnum(SimpleEnum.TWO);
dtoImpl.getFooStrings().add(fooString);
dtoImpl.getNightmare();
dtoImpl.getArrayOfArrayOfEnum();
// Assume that SimpleDto works. Use it to test nested objects
SimpleDtoImpl simpleDto = SimpleDtoImpl.make();
simpleDto.setName(fooString);
simpleDto.setIDontStartWithGet(intId);
dtoImpl.getSimpleDtos().add(simpleDto);
dtoImpl.getMap().put(fooString, simpleDto);
// Check to make sure things are in a sane state.
ComplicatedDto dto = dtoImpl;
assertEquals(intId, dto.getIntId());
assertEquals(fooString, dto.getFooStrings().get(0));
// Should be reference equal initially.
assertEquals(dto.getSimpleDtos().get(0), simpleDto);
assertEquals(dto.getMap().get(fooString), simpleDto);
assertEquals(ComplicatedDto.TYPE, dto.getType());
// Make it json and pull it back out.
Gson gson = new Gson();
String serialized = dtoToJson(gson, dtoImpl);
ComplicatedDtoImpl deserialized = ComplicatedDtoImpl.fromJsonString(serialized);
// Test correctness of JSON serialization.
assertEquals(serialized, dtoImpl.toJson());
assertEquals(intId, deserialized.getIntId());
assertEquals(fooString, deserialized.getFooStrings().get(0));
assertEquals(ComplicatedDto.TYPE, deserialized.getType());
// Pull it out using the DTO's deserializer.
JsonElement jsonElement = new JsonParser().parse(serialized);
ComplicatedDtoImpl deserialized2 = ComplicatedDtoImpl.fromJsonElement(jsonElement);
assertEquals(intId, deserialized2.getIntId());
assertEquals(fooString, deserialized2.getFooStrings().get(0));
assertEquals(ComplicatedDto.TYPE, deserialized2.getType());
// Verify that the hasFields() are correct when using the DTO's deserializer.
assertTrue(deserialized2.hasIntId());
// Check that the SimpleDto object looks correct.
checkSimpleDto(dto.getSimpleDtos().get(0), simpleDto.getName(), simpleDto.iDontStartWithGet());
checkSimpleDto(dto.getMap().get(fooString), simpleDto.getName(), simpleDto.iDontStartWithGet());
}
public void testNotRoutableImpl() {
final String fooString = "Something";
NotRoutableImpl dtoImpl = new NotRoutableImpl();
dtoImpl.setSomeField(fooString);
// Make it json and pull it back out.
Gson gson = new Gson();
String serialized = gson.toJson(dtoImpl);
NotRoutable dto = NotRoutableImpl.fromJsonString(serialized);
assertEquals(fooString, dto.getSomeField());
}
public void testNullEnum() {
ComplicatedDtoImpl dtoImpl = ComplicatedDtoImpl.make();
dtoImpl.setIntId(1);
dtoImpl.setSimpleEnum(null);
// Make it json and pull it back out.
Gson gson = new GsonBuilder().serializeNulls().create();
String serialized = dtoImpl.toJson();
assertEquals(dtoToJson(gson, dtoImpl), serialized);
ComplicatedDto dto = ComplicatedDtoImpl.fromJsonString(serialized);
assertEquals(1, dto.getIntId());
assertNull(dto.getSimpleEnum());
}
public void testSimpleDtoImpl() {
final String fooString = "Something";
final int intValue = 1;
SimpleDtoImpl dtoImpl = SimpleDtoImpl.make();
dtoImpl.setName("Something");
dtoImpl.setIDontStartWithGet(intValue);
checkSimpleDto(dtoImpl, fooString, intValue);
// Make it json and pull it back out.
Gson gson = new Gson();
String serialized = gson.toJson(dtoImpl);
SimpleDto dto = SimpleDtoImpl.fromJsonString(serialized);
checkSimpleDto(dto, fooString, intValue);
}
public void testSimpleDtoImpl_deserialize() {
final String fooString = "Something";
JsonObject json = new JsonObject();
json.add("name", new JsonPrimitive(fooString));
SimpleDtoImpl deserialized = SimpleDtoImpl.fromJsonElement(json);
assertTrue(deserialized.hasName());
assertFalse(deserialized.hasIDontStartWithGet());
checkSimpleDto(deserialized, fooString, 0);
}
public void testSimpleDtoImpl_nullStringSerialization() {
final String fooString = null;
final int intValue = 1;
SimpleDtoImpl dtoImpl = SimpleDtoImpl.make();
dtoImpl.setName(fooString);
dtoImpl.setIDontStartWithGet(intValue);
checkSimpleDto(dtoImpl, fooString, intValue);
// Make it json and pull it back out.
Gson gson = new GsonBuilder().serializeNulls().create();
String serialized = dtoImpl.toJson();
assertEquals(dtoToJson(gson, dtoImpl), serialized);
SimpleDto dto = SimpleDtoImpl.fromJsonString(serialized);
checkSimpleDto(dto, fooString, intValue);
}
private void checkSimpleDto(SimpleDto dto, String expectedName, int expectedNum) {
assertEquals(expectedName, dto.getName());
assertEquals(expectedNum, dto.iDontStartWithGet());
assertEquals(SimpleDto.TYPE, dto.getType());
}
public void testSimpleDtoSubtypeImpl() {
final String valueForFieldOnSupertype = "valueForFieldOnSupertype";
final String valueForFieldOnSelf = "valueForFieldOnSelf";
SimpleDtoSubTypeImpl dto = SimpleDtoSubTypeImpl.make();
dto.setName(valueForFieldOnSupertype);
dto.setAnotherField(valueForFieldOnSelf);
String json = dto.toJson();
assertTrue(json.contains(valueForFieldOnSelf));
assertTrue(json.contains(valueForFieldOnSupertype));
}
public void testEqualsAndHashCode() {
final String fooString = "something";
final String barString = "something else";
final String bazString = "something else, again";
final String fluxString = "yet something ELSE";
final int fooNum = 4;
final int barNum = 5;
SimpleDtoSubTypeImpl dtoA = SimpleDtoSubTypeImpl.make();
SimpleDtoSubTypeImpl dtoB = SimpleDtoSubTypeImpl.make();
checkEqualsAndHashCode(dtoA, dtoB, true);
// test on an object field
dtoA.setName(fooString);
assert(dtoA.hasName());
assertFalse(dtoB.hasName());
checkEqualsAndHashCode(dtoA, dtoB, false);
dtoB.setName(fooString);
checkEqualsAndHashCode(dtoA, dtoB, true);
dtoA.setName(barString);
checkEqualsAndHashCode(dtoA, dtoB, false);
dtoA.setName(fooString);
checkEqualsAndHashCode(dtoA, dtoB, true);
// test on a primitive field
dtoA.setNumber(fooNum);
checkEqualsAndHashCode(dtoA, dtoB, false);
dtoB.setNumber(fooNum);
checkEqualsAndHashCode(dtoA, dtoB, true);
dtoA.setNumber(barNum);
checkEqualsAndHashCode(dtoA, dtoB, false);
dtoA.setNumber(fooNum);
checkEqualsAndHashCode(dtoA, dtoB, true);
// test on a subclass' field
dtoA.setAnotherField(bazString);
checkEqualsAndHashCode(dtoA, dtoB, false);
dtoB.setAnotherField(bazString);
checkEqualsAndHashCode(dtoA, dtoB, true);
dtoA.setAnotherField(fluxString);
checkEqualsAndHashCode(dtoA, dtoB, false);
dtoA.setAnotherField(bazString);
checkEqualsAndHashCode(dtoA, dtoB, true);
}
private void checkEqualsAndHashCode(Object a, Object b, boolean shouldBeEqual) {
assertTrue(a.equals(a));
assertTrue(b.equals(b));
assertTrue(a.equals(b) == shouldBeEqual);
assertTrue(b.equals(a) == shouldBeEqual);
if (shouldBeEqual) {
assertEquals(a, b);
assertEquals(b, a);
}
// if a and b are not equal, their hashcodes could still collide if we are unlucky, but since
// this test uses static data for all objects, we can ensure this doesn't happen
assertTrue((a.hashCode() == b.hashCode()) == shouldBeEqual);
}
/**
* Converts the object to JSON, removing all _has fields.
*
* @param gson the Gson used to parse the object
*/
private String dtoToJson(Gson gson, ServerToClientDto dtoImpl) {
com.google.gson.JsonObject jsonObj = gson.toJsonTree(dtoImpl).getAsJsonObject();
stripHasFields(jsonObj);
return gson.toJson(jsonObj);
}
/**
* Recursively strip fields that start with _has from the specified object. Modifies the object.
*/
private void stripHasFields(JsonElement jsonElem) {
if (jsonElem.isJsonObject()) {
com.google.gson.JsonObject jsonObj = jsonElem.getAsJsonObject();
// Determine which fields should be removed.
Set<String> hasFields = new HashSet<String>();
for (Map.Entry<String, JsonElement> field : jsonObj.entrySet()) {
if (field.getKey().startsWith("_has")) {
// Remove the _hasAbc field.
hasFields.add(field.getKey());
} else {
// Recursively strip fields on the child.
stripHasFields(field.getValue());
}
}
// Remove the fields.
for (String hasField : hasFields) {
jsonObj.remove(hasField);
}
} else if (jsonElem.isJsonArray()) {
JsonArray array = jsonElem.getAsJsonArray();
// Recursively call on child objects in an array.
for (int i = 0; i < array.size(); i++) {
stripHasFields(array.get(i));
}
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/dtogen/client/ClientImplTest.java | javatests/com/google/collide/dtogen/client/ClientImplTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.dtogen.client;
import com.google.collide.dtogen.client.TestDtoClientImpls.ComplicatedDtoImpl;
import com.google.collide.dtogen.client.TestDtoClientImpls.NotRoutableImpl;
import com.google.collide.dtogen.client.TestDtoClientImpls.SimpleDtoImpl;
import com.google.collide.dtogen.definitions.ComplicatedDto;
import com.google.collide.dtogen.definitions.ComplicatedDto.SimpleEnum;
import com.google.collide.dtogen.definitions.NotRoutable;
import com.google.collide.dtogen.definitions.SimpleDto;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonArray;
import com.google.gwt.junit.client.GWTTestCase;
/**
* Tests that the interfaces specified in com.google.gwt.dto.definitions have
* corresponding generated Client impls.
*
*/
public class ClientImplTest extends GWTTestCase {
private static native NotRoutableImpl getNotRoutable() /*-{
return {};
}-*/;
@Override
public String getModuleName() {
return "com.google.collide.dtogen.ClientImplTestModule";
}
public void testComplicatedDtoImpl() {
final String fooString = "Something";
final int intId = 1;
SimpleDto simpleDto = SimpleDtoImpl.make().setName(fooString).setIDontStartWithGet(intId);
@SuppressWarnings("unchecked")
JsoArray<JsoArray<SimpleEnum>> arrArrEnum =
JsoArray.from(JsoArray.from(SimpleEnum.ONE, SimpleEnum.TWO, SimpleEnum.THREE),
JsoArray.from(SimpleEnum.TWO, SimpleEnum.THREE), JsoArray.from(SimpleEnum.THREE));
ComplicatedDto dto =
ComplicatedDtoImpl.make().setIntId(intId).setMap(JsoStringMap.<SimpleDto>create())
.setSimpleDtos(JsoArray.<SimpleDto>create()).setFooStrings(JsoArray.<String>create())
.setArrayOfArrayOfEnum(arrArrEnum);
dto.getFooStrings().add(fooString);
dto.getSimpleDtos().add(simpleDto);
assertEquals(intId, dto.getIntId());
assertEquals(fooString, dto.getFooStrings().get(0));
assertEquals(simpleDto, dto.getSimpleDtos().get(0));
assertTrue(areArraysEqual(arrArrEnum, dto.getArrayOfArrayOfEnum()));
assertEquals(ComplicatedDto.TYPE, dto.getType());
}
private static native final boolean areArraysEqual(JsonArray<?> arr1, JsonArray<?> arr2) /*-{
// Lists can't be tested for equality with "==", but "<" and ">" work.
// This creates "equality" by making sure that arr1 >= arr2 && arr1 <= arr2
return !(arr1 < arr2) && !(arr1 > arr2);
}-*/;
public void testNotRoutableImpl() {
final String fooString = "Something";
NotRoutable dto = getNotRoutable().setSomeField(fooString);
assertEquals(fooString, dto.getSomeField());
}
public void testSimpleDtoImpl() {
final String nameString = "Something";
final int intValue = 1;
SimpleDto dto = SimpleDtoImpl.make().setName(nameString).setIDontStartWithGet(intValue);
assertEquals(nameString, dto.getName());
assertEquals(intValue, dto.iDontStartWithGet());
assertEquals(SimpleDto.TYPE, dto.getType());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/server/plugin/gwt/GwtPluginTest.java | javatests/com/google/collide/server/plugin/gwt/GwtPluginTest.java | package com.google.collide.server.plugin.gwt;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import junit.framework.TestCase;
import org.junit.Test;
import org.vertx.java.busmods.BusModBase;
import org.vertx.java.core.Handler;
import org.vertx.java.core.Vertx;
import org.vertx.java.core.VertxFactory;
import org.vertx.java.core.eventbus.Message;
import org.vertx.java.core.impl.DefaultVertx;
import org.vertx.java.core.impl.VertxInternal;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.deploy.Container;
import org.vertx.java.deploy.impl.VerticleManager;
import org.vertx.java.deploy.impl.VertxLocator;
import com.google.collide.plugin.server.PluginManager;
import com.google.collide.plugin.server.gwt.GwtServerPlugin;
import com.google.collide.server.shared.util.Dto;
import collide.shared.manifest.CollideManifest;
public class GwtPluginTest extends TestCase {
private VertxInternal vertx;
private BusModBase pluginManager;
@Override
protected void setUp() throws Exception {
super.setUp();
pluginManager = new PluginManager();
pluginManager.setVertx(vertx);
vertx = new DefaultVertx(18080, "0.0.0.0");
VerticleManager verticleManager = new VerticleManager(vertx);
Map<String, Object> map = new HashMap<String, Object>();
//for now, let's just setup default collide
map.put("plugins", new JsonArray().addString("gwt"));
map.put("includes", new JsonArray().addString("gwt"));
map.put("preserve-cwd", true);
map.put("webRoot", new File(".").getCanonicalPath());
File location;
location = new File (
GwtPluginTest.class
.getProtectionDomain().getCodeSource().getLocation()
.toExternalForm().replace("file:", "")
);
while (location != null && !"classes".equals(location.getName())) {
location = location.getParentFile();
}
location = new File(location, "lib");
String libFolder = location.getCanonicalPath();
map.put("staticFiles", libFolder);
JsonObject jsonConfig = new JsonObject(map );
ClassLoader cl = getClass().getClassLoader();
ArrayList<URL> urlList = new ArrayList<>();
while (cl != null) {
if (cl instanceof URLClassLoader) {
URLClassLoader urls = (URLClassLoader)cl;
for (URL url : urls.getURLs()){
urlList.add(url);
}
}
}
libFolder = "file:"+libFolder;
System.out.println(urlList);
URL[] urls = urlList.toArray(new URL[urlList.size()]);
// verticleManager.deployVerticle(true,
// "com.google.collide.plugin.server.gwt.GwtPluginTest", jsonConfig,
// urls, 1, new File("."),"*", new Handler<String>() {
// @Override
// public void handle(String deployId) {
//
// }
// });
// Container container = new Container(verticleManager );
//
// pluginManager.setContainer(container);
}
@Test(timeout = 300000)
public void testCompiler() {
GwtServerPlugin plugin = new GwtServerPlugin();
plugin.initialize(vertx);
vertx.eventBus().registerHandler("gwt.log", new Handler<Message<JsonObject>>() {
@Override
public void handle(Message<JsonObject> arg0) {
System.out.println("gwtlog: " + arg0.body);
}
});
final JsonObject req =
Dto.wrap("{"
+ "module : 'collide.demo.Foreign'"
+ ",src : ['api/src/main/java', 'shared/src/main/java','client/src/main/java','client/src/main/resources','xapi-gwt.jar']"
+ ",deps : ['elemental.jar', 'gwt-dev.jar', 'gwt-user.jar']" +
"}");
for (Map.Entry<String, Handler<Message<JsonObject>>> handles : plugin.getHandlers().entrySet()) {
vertx.eventBus().registerHandler("gwt." + handles.getKey(), handles.getValue());
}
final AtomicBoolean bool = new AtomicBoolean(true);
vertx.eventBus().send("gwt.compile", req, new Handler<Message<JsonObject>>() {
@Override
public void handle(Message<JsonObject> arg0) {
System.out.println("received " + arg0.body);
bool.set(false);
}
});
// now we must block for a while to keep the thread alive for compile
int i = 500;// we're going to block for 100 seconds
while (i-- > 0 && bool.get())
// or until the compile finishes
try {
Thread.sleep(200);
} catch (Exception e) {
return;
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/server/filetree/FileTreeExperiment.java | javatests/com/google/collide/server/filetree/FileTreeExperiment.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.server.filetree;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class FileTreeExperiment {
public static void main(String[] args) throws IOException, InterruptedException {
final Map<WatchKey, Path> map = new HashMap<WatchKey, Path>();
final Path rootPath = new File("").toPath();
final WatchService watcher = FileSystems.getDefault().newWatchService();
final Stack<Path> parents = new Stack<Path>();
final FileVisitor<Path> visitor = new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs)
throws IOException {
if (parents.isEmpty()) {
// root
System.out.println("scanning from: " + path.toAbsolutePath() + '/');
} else {
System.out.println("add: /" + path + '/');
}
parents.push(path);
WatchKey key = path.register(
watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW);
map.put(key, path);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) {
System.out.println("add: /" + path);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
System.out.println("visitFileFailed: " + file);
throw exc;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (exc != null) {
System.out.println("postVisitDirectory failed: " + dir);
throw exc;
}
parents.pop();
return FileVisitResult.CONTINUE;
}
};
Files.walkFileTree(rootPath, visitor);
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
Files.createDirectory(rootPath.resolve("tmp"));
Files.createDirectory(rootPath.resolve("tmp/dir"));
Files.createFile(rootPath.resolve("tmp/file"));
Files.createFile(rootPath.resolve("tmp/dir/file2"));
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
for (;;) {
// retrieve key
WatchKey key = watcher.take();
Path parent = map.get(key);
System.out.println("-----");
// process events
for (WatchEvent<?> event : key.pollEvents()) {
if (event.kind().type() == Path.class) {
Path path = (Path) event.context();
Path resolved = parent.resolve(path);
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("cre: /" + resolved);
parents.push(parent);
Files.walkFileTree(resolved, visitor);
parents.pop();
} else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
System.out.println("mod: /" + resolved);
} else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println("del: /" + resolved);
} else {
assert false : "Unknown event type: " + event.kind().name();
}
} else {
assert event.kind() == StandardWatchEventKinds.OVERFLOW;
System.out.print(event.kind().name() + ": ");
System.out.println(event.count());
}
}
// reset the key
boolean valid = key.reset();
if (!valid) {
// object no longer registered
map.remove(key);
}
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/TestHelper.java | javatests/com/google/collide/client/TestHelper.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client;
public class TestHelper {
private TestHelper() {
// uninstantiable
}
public static void setupPlaces(AppContext context) {
Collide.setUpPlaces(context);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/util/HoverControllerTest.java | javatests/com/google/collide/client/util/HoverControllerTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.util;
import collide.client.util.Elements;
import com.google.collide.client.util.HoverController.HoverListener;
import com.google.collide.client.util.HoverController.UnhoverListener;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.user.client.Timer;
import elemental.dom.Document;
import elemental.dom.Element;
import elemental.events.MouseEvent;
/**
* Tests for {@link HoverController}.
*
*/
public class HoverControllerTest extends GWTTestCase {
private static class MockHoverListener implements HoverListener, UnhoverListener {
private int hoverCalled;
private int unhoverCalled;
public void assertHoverCount(int expected) {
assertEquals(expected, hoverCalled);
}
public void assertUnhoverCount(int expected) {
assertEquals(expected, unhoverCalled);
}
@Override
public void onHover() {
hoverCalled++;
}
@Override
public void onUnhover() {
unhoverCalled++;
}
}
@Override
public String getModuleName() {
return "com.google.collide.client.util.UtilTestModule";
}
/**
* Tests a basic hover/unhover sequence.
*/
public void testBasicHoverSequence() {
final MockHoverListener listener = new MockHoverListener();
final Element[] elems = createAndAttachElements(3);
HoverController controller = new HoverController();
controller.setHoverListener(listener);
controller.setUnhoverListener(listener);
controller.setUnhoverDelay(25);
controller.addPartner(elems[0]);
controller.addPartner(elems[1]);
controller.addPartner(elems[2]);
listener.assertHoverCount(0);
listener.assertUnhoverCount(0);
// Mouseover an element. onHover() called synchronously.
mouseover(elems[1]);
listener.assertHoverCount(1);
listener.assertUnhoverCount(0);
// Mouseout an element. onUnhover() is not called because we are still in
// the unhover delay.
mouseout(elems[2]);
listener.assertHoverCount(1);
listener.assertUnhoverCount(0);
// Wait for the unhover delay.
delayTestFinish(1000);
new Timer() {
@Override
public void run() {
listener.assertHoverCount(1);
listener.assertUnhoverCount(1);
// Cleanup.
detachElements(elems);
finishTest();
}
}.schedule(100);
}
/**
* Tests that once we start hovering, subsequent mouseover events do not call
* {@link MockHoverListener#onHover()}.
*/
public void testMouseoverWhileHovering() {
final MockHoverListener listener = new MockHoverListener();
final Element[] elems = createAndAttachElements(3);
HoverController controller = new HoverController();
controller.setHoverListener(listener);
controller.setUnhoverListener(listener);
controller.setUnhoverDelay(25);
controller.addPartner(elems[0]);
controller.addPartner(elems[1]);
controller.addPartner(elems[2]);
listener.assertHoverCount(0);
listener.assertUnhoverCount(0);
// Mouseover an element. onHover() is called synchronously.
mouseover(elems[1]);
listener.assertHoverCount(1);
listener.assertUnhoverCount(0);
// Mouseover another element.
mouseover(elems[2]);
listener.assertHoverCount(1);
listener.assertUnhoverCount(0);
// Mouseover the same element.
mouseover(elems[2]);
listener.assertHoverCount(1);
listener.assertUnhoverCount(0);
// Cleanup.
detachElements(elems);
}
/**
* Tests that if the user mouses over an element after mousing out of an
* element, but before the unhover delay fires, then
* {@link UnhoverListener#onUnhover()} is not called.
*/
public void testMouseoverWithinUnhoverDelay() {
final MockHoverListener listener = new MockHoverListener();
final Element[] elems = createAndAttachElements(3);
HoverController controller = new HoverController();
controller.setHoverListener(listener);
controller.setUnhoverListener(listener);
controller.setUnhoverDelay(25);
controller.addPartner(elems[0]);
controller.addPartner(elems[1]);
controller.addPartner(elems[2]);
listener.assertHoverCount(0);
listener.assertUnhoverCount(0);
// mouseover an element. onHover() called synchronously.
mouseover(elems[1]);
listener.assertHoverCount(1);
listener.assertUnhoverCount(0);
// mouseout an element. onUnhover() is not called because we are still in
// the unhover delay.
mouseout(elems[2]);
listener.assertHoverCount(1);
listener.assertUnhoverCount(0);
// mouseover within the delay. onUnhover() is cancelled.
mouseover(elems[2]);
listener.assertHoverCount(1);
listener.assertUnhoverCount(0);
// Verify unhover is never called.
delayTestFinish(1000);
new Timer() {
@Override
public void run() {
listener.assertHoverCount(1);
listener.assertUnhoverCount(0);
// Cleanup.
detachElements(elems);
finishTest();
}
}.schedule(100);
}
/**
* Tests that nothing breaks if no listeners are set.
*/
public void testNoListeners() {
final Element[] elems = createAndAttachElements(3);
HoverController controller = new HoverController();
controller.setUnhoverDelay(0);
controller.addPartner(elems[0]);
controller.addPartner(elems[1]);
controller.addPartner(elems[2]);
// mouseover an element.
mouseover(elems[1]);
// mouseout an element.
mouseout(elems[2]);
// Cleanup.
detachElements(elems);
}
/**
* Tests that setting the unhover delay to a negative value prevents
* {@link UnhoverListener#onUnhover()} from being called.
*/
public void testSetUnhoverDelayNevagtive() {
final MockHoverListener listener = new MockHoverListener();
final Element[] elems = createAndAttachElements(3);
HoverController controller = new HoverController();
controller.setHoverListener(listener);
controller.setUnhoverListener(listener);
controller.setUnhoverDelay(-1);
controller.addPartner(elems[0]);
controller.addPartner(elems[1]);
controller.addPartner(elems[2]);
listener.assertHoverCount(0);
listener.assertUnhoverCount(0);
// mouseover an element. onHover() called synchronously.
mouseover(elems[1]);
listener.assertHoverCount(1);
listener.assertUnhoverCount(0);
// mouseout an element. onUnhover() not called.
mouseout(elems[2]);
listener.assertHoverCount(1);
listener.assertUnhoverCount(0);
// Verify unhover is never called.
delayTestFinish(1000);
new Timer() {
@Override
public void run() {
listener.assertHoverCount(1);
listener.assertUnhoverCount(0);
// Cleanup.
detachElements(elems);
finishTest();
}
}.schedule(100);
}
/**
* Tests that setting the unhover delay to zero forces
* {@link UnhoverListener#onUnhover()} to be called synchronously.
*/
public void testSetUnhoverDelayZero() {
final MockHoverListener listener = new MockHoverListener();
final Element[] elems = createAndAttachElements(3);
HoverController controller = new HoverController();
controller.setHoverListener(listener);
controller.setUnhoverListener(listener);
controller.setUnhoverDelay(0);
controller.addPartner(elems[0]);
controller.addPartner(elems[1]);
controller.addPartner(elems[2]);
listener.assertHoverCount(0);
listener.assertUnhoverCount(0);
// mouseover an element. onHover() called synchronously.
mouseover(elems[1]);
listener.assertHoverCount(1);
listener.assertUnhoverCount(0);
// mouseout an element. onUnhover() called synchronously.
mouseout(elems[2]);
listener.assertHoverCount(1);
listener.assertUnhoverCount(1);
// Cleanup.
detachElements(elems);
}
private Element[] createAndAttachElements(int count) {
Document doc = Elements.getDocument();
Element[] elems = new Element[count];
for (int i = 0; i < count; i++) {
Element elem = doc.createDivElement();
doc.getBody().appendChild(elem);
elems[i] = elem;
}
return elems;
}
private void mouseevent(Element target, String type) {
MouseEvent evt = (MouseEvent) Elements.getDocument().createEvent(Document.Events.MOUSE);
evt.initMouseEvent(type, true, true, null, 0, 0, 0, 0, 0, false, false, false, false,
MouseEvent.Button.PRIMARY, null);
target.dispatchEvent(evt);
}
private void mouseout(Element target) {
mouseevent(target, "mouseout");
}
private void mouseover(Element target) {
mouseevent(target, "mouseover");
}
private void detachElements(Element[] elems) {
for (Element elem : elems) {
elem.removeFromParent();
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/util/AnimationControllerTest.java | javatests/com/google/collide/client/util/AnimationControllerTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.util;
import collide.client.util.Elements;
import com.google.collide.client.util.AnimationController.State;
import com.google.gwt.junit.client.GWTTestCase;
import elemental.dom.Element;
/**
* Tests for {@link AnimationController}.
*
* Most of the methods in this test only execute on browsers that support
* animations.
*/
public class AnimationControllerTest extends GWTTestCase {
/**
* Check if the browser under test supports animations.
*/
private static boolean isAnimationSupported() {
AnimationController ac = new AnimationController.Builder().setFade(true).build();
return ac.isAnimated;
}
/**
* Check if a command is scheduled to execute on the specified element.
*
* @param elem
*/
private static native boolean isCommandScheduled(Element elem) /*-{
return elem.__gwtLastCommand != null;
}-*/;
@Override
public String getModuleName() {
return "com.google.collide.client.util.UtilTestModule";
}
/**
* Test that the element is hidden synchronously if there are no animations.
*/
public void testHideNoAnimation() {
Element elem = Elements.createDivElement();
AnimationController ac = AnimationController.NO_ANIMATION_CONTROLLER;
assertFalse(ac.isAnimated);
// Start the test with the element shown.
ac.showWithoutAnimating(elem);
assertTrue(ac.isAnyState(elem, State.SHOWN));
// Hide the element.
ac.hide(elem);
assertTrue(ac.isAnyState(elem, State.HIDDEN));
assertFalse(isCommandScheduled(elem));
}
public void testHideWithoutAnimating() {
Element elem = Elements.createDivElement();
AnimationController ac = AnimationController.NO_ANIMATION_CONTROLLER;
assertFalse(ac.isAnimated);
assertFalse(ac.isAnyState(elem, State.HIDDEN));
ac.hideWithoutAnimating(elem);
assertTrue(ac.isAnyState(elem, State.HIDDEN));
assertFalse(isCommandScheduled(elem));
}
/**
* Test that the element is shown synchronously if there are no animations.
*/
public void testShowNoAnimation() {
Element elem = Elements.createDivElement();
AnimationController ac = AnimationController.NO_ANIMATION_CONTROLLER;
assertFalse(ac.isAnimated);
assertFalse(ac.isAnyState(elem, State.SHOWN));
ac.show(elem);
assertTrue(ac.isAnyState(elem, State.SHOWN));
assertFalse(isCommandScheduled(elem));
}
public void testShowWithoutAnimating() {
Element elem = Elements.createDivElement();
AnimationController ac = AnimationController.NO_ANIMATION_CONTROLLER;
assertFalse(ac.isAnimated);
assertFalse(ac.isAnyState(elem, State.SHOWN));
ac.showWithoutAnimating(elem);
assertTrue(ac.isAnyState(elem, State.SHOWN));
assertFalse(isCommandScheduled(elem));
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/util/ReordererTest.java | javatests/com/google/collide/client/util/ReordererTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.util;
import com.google.collide.shared.util.Reorderer;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.user.client.Timer;
/*
* The reason these are in the client is because Reorderer used to be client-only, but was moved
* to shared code, but the tests weren't migrated to be pure java.
*/
/**
* Tests for {@link Reorderer}.
*/
public class ReordererTest extends GWTTestCase {
private static class ItemSink implements Reorderer.ItemSink<Integer> {
int lastVersion;
ItemSink(int firstExpectedVersion) {
this.lastVersion = firstExpectedVersion - 1;
}
@Override
public void onItem(Integer item, int version) {
assertEquals(++lastVersion, version);
assertEquals(item.intValue(), version);
}
}
private class RequiredTimeoutCallback implements Reorderer.TimeoutCallback {
private int requiredLastVersionDispatched;
RequiredTimeoutCallback(int requiredLastVersionDispatched) {
this.requiredLastVersionDispatched = requiredLastVersionDispatched;
}
@Override
public void onTimeout(int lastVersionDispatched) {
assertEquals(requiredLastVersionDispatched, lastVersionDispatched);
finishTest();
}
}
private static final Reorderer.TimeoutCallback FAIL_TIMEOUT_CALLBACK =
new Reorderer.TimeoutCallback() {
@Override
public void onTimeout(int lastVersionDispatched) {
fail("Timeout should not have been called");
}
};
Reorderer<Integer> reorderer;
ItemSink sink;
@Override
public String getModuleName() {
return "com.google.collide.client.util.UtilTestModule";
}
public void testInOrder() {
{
ItemSink sink = new ItemSink(1);
Reorderer<Integer> reorderer =
Reorderer.create(1, sink, 1, FAIL_TIMEOUT_CALLBACK, ClientTimer.FACTORY);
reorderer.acceptItem(1, 1);
reorderer.acceptItem(2, 2);
reorderer.acceptItem(3, 3);
reorderer.acceptItem(4, 4);
reorderer.acceptItem(5, 5);
assertEquals(sink.lastVersion, 5);
}
{
ItemSink sink = new ItemSink(3);
Reorderer<Integer> reorderer =
Reorderer.create(3, sink, 1, FAIL_TIMEOUT_CALLBACK, ClientTimer.FACTORY);
reorderer.acceptItem(3, 3);
reorderer.acceptItem(4, 4);
reorderer.acceptItem(5, 5);
assertEquals(sink.lastVersion, 5);
}
}
public void testOutOfOrderNoTimeout() {
{
// Immediate out-of-order
ItemSink sink = new ItemSink(1);
Reorderer<Integer> reorderer =
Reorderer.create(1, sink, Integer.MAX_VALUE, FAIL_TIMEOUT_CALLBACK, ClientTimer.FACTORY);
reorderer.acceptItem(2, 2);
reorderer.acceptItem(1, 1);
assertEquals(sink.lastVersion, 2);
}
{
// Two out-of-order
ItemSink sink = new ItemSink(1);
Reorderer<Integer> reorderer =
Reorderer.create(1, sink, Integer.MAX_VALUE, FAIL_TIMEOUT_CALLBACK, ClientTimer.FACTORY);
reorderer.acceptItem(1, 1);
reorderer.acceptItem(2, 2);
reorderer.acceptItem(5, 5);
reorderer.acceptItem(4, 4);
reorderer.acceptItem(3, 3);
assertEquals(sink.lastVersion, 5);
}
{
// Massive out-of-order
ItemSink sink = new ItemSink(1);
Reorderer<Integer> reorderer =
Reorderer.create(1, sink, Integer.MAX_VALUE, FAIL_TIMEOUT_CALLBACK, ClientTimer.FACTORY);
reorderer.acceptItem(5, 5);
reorderer.acceptItem(3, 3);
reorderer.acceptItem(1, 1);
reorderer.acceptItem(4, 4);
reorderer.acceptItem(2, 2);
assertEquals(sink.lastVersion, 5);
}
}
public void testOutOfOrderTimeout() {
ItemSink sink = new ItemSink(1);
RequiredTimeoutCallback timeoutCallback = new RequiredTimeoutCallback(3);
Reorderer<Integer> reorderer =
Reorderer.create(1, sink, 1, timeoutCallback, ClientTimer.FACTORY);
reorderer.acceptItem(1, 1);
reorderer.acceptItem(2, 2);
reorderer.acceptItem(3, 3);
reorderer.acceptItem(5, 5);
assertEquals(sink.lastVersion, 3);
delayTestFinish(100);
}
public void testOutOfOrderThenFillInGapThenTimeout() {
ItemSink sink = new ItemSink(1);
RequiredTimeoutCallback timeoutCallback = new RequiredTimeoutCallback(4);
Reorderer<Integer> reorderer =
Reorderer.create(1, sink, 1, timeoutCallback, ClientTimer.FACTORY);
reorderer.acceptItem(1, 1);
reorderer.acceptItem(3, 3);
reorderer.acceptItem(4, 4);
reorderer.acceptItem(6, 6);
reorderer.acceptItem(2, 2);
assertEquals(sink.lastVersion, 4);
delayTestFinish(100);
}
public void testOutOfOrderTimeoutDisabled() {
ItemSink sink = new ItemSink(1);
Reorderer<Integer> reorderer =
Reorderer.create(1, sink, 1, FAIL_TIMEOUT_CALLBACK, ClientTimer.FACTORY);
reorderer.setTimeoutEnabled(false);
reorderer.acceptItem(1, 1);
reorderer.acceptItem(2, 2);
reorderer.acceptItem(3, 3);
reorderer.acceptItem(5, 5);
assertEquals(sink.lastVersion, 3);
ensureThatFailTimeoutWillNotBeCalled();
}
public void testOutOfOrderTimeoutDisabledAndThenEnabled() {
ItemSink sink = new ItemSink(1);
RequiredTimeoutCallback timeoutCallback = new RequiredTimeoutCallback(3);
Reorderer<Integer> reorderer =
Reorderer.create(1, sink, 1, timeoutCallback, ClientTimer.FACTORY);
reorderer.setTimeoutEnabled(false);
reorderer.acceptItem(1, 1);
reorderer.acceptItem(2, 2);
reorderer.acceptItem(3, 3);
reorderer.acceptItem(5, 5);
assertEquals(sink.lastVersion, 3);
reorderer.setTimeoutEnabled(true);
delayTestFinish(100);
}
public void testSkipToVersion() {
ItemSink sink = new ItemSink(1);
Reorderer<Integer> reorderer =
Reorderer.create(1, sink, 1, FAIL_TIMEOUT_CALLBACK, ClientTimer.FACTORY);
reorderer.acceptItem(1, 1);
reorderer.acceptItem(2, 2);
reorderer.acceptItem(3, 3);
reorderer.acceptItem(5, 5);
reorderer.acceptItem(6, 6);
reorderer.acceptItem(8, 8);
reorderer.acceptItem(7, 7);
assertEquals(sink.lastVersion, 3);
/*
* The timeout callback would normally be called, but our skipToVersion below will cancel it and
* get us back on track. It will also try to process any queued doc ops including the given
* version (5) and after.
*/
// Override what the sink should expect next
sink.lastVersion = 4;
reorderer.skipToVersion(5);
assertEquals(sink.lastVersion, 8);
ensureThatFailTimeoutWillNotBeCalled();
}
public void testQueueUntilSkipToVersionCalled() {
ItemSink sink = new ItemSink(5);
Reorderer<Integer> reorderer =
Reorderer.create(0, sink, 1, FAIL_TIMEOUT_CALLBACK, ClientTimer.FACTORY);
reorderer.queueUntilSkipToVersionIsCalled();
reorderer.acceptItem(5, 5);
reorderer.acceptItem(6, 6);
reorderer.acceptItem(7, 7);
assertNotSame(7, sink.lastVersion);
reorderer.skipToVersion(5);
assertEquals(7, sink.lastVersion);
ensureThatFailTimeoutWillNotBeCalled();
}
private void ensureThatFailTimeoutWillNotBeCalled() {
new Timer() {
@Override
public void run() {
/*
* If the timeout was still enabled, FAIL_TIMEOUT_CALLBACK would have been queued/will run
* before this logic does
*/
finishTest();
}
}.schedule(1);
delayTestFinish(100);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/util/ClientStringUtilsTest.java | javatests/com/google/collide/client/util/ClientStringUtilsTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.util;
import com.google.gwt.junit.client.GWTTestCase;
/**
*
*/
public class ClientStringUtilsTest extends GWTTestCase {
public static final String SEP = PathUtil.SEP;
@Override
public String getModuleName() {
return "com.google.collide.client.util.UtilTestModule";
}
public void testNoEllipsis() {
// Ensure both variations do not have ellipsis
String stringPath = "/simple/path.txt";
PathUtil path = new PathUtil(stringPath);
String result = ClientStringUtils.ellipsisPath(path, 2, 0, SEP);
assertEquals(stringPath, result);
result = ClientStringUtils.ellipsisPath(new PathUtil(stringPath.substring(1)), 2, 0, SEP);
assertEquals(stringPath, result);
stringPath = "/short.txt";
result = ClientStringUtils.ellipsisPath(new PathUtil(stringPath), 2, 0, SEP);
assertEquals(stringPath, result);
stringPath = "/some/path/short.txt";
result = ClientStringUtils.ellipsisPath(new PathUtil(stringPath), 5, 0, SEP);
assertEquals(stringPath, result);
}
public void testEllipsisPaths() {
String stringPath = "/my/simple/path.txt";
PathUtil path = new PathUtil(stringPath);
String result = ClientStringUtils.ellipsisPath(path, 2, 0, SEP);
assertEquals("../simple/path.txt", result);
result = ClientStringUtils.ellipsisPath(path, 1, 0, SEP);
assertEquals("../path.txt", result);
result = ClientStringUtils.ellipsisPath(path, 5, 0, SEP);
assertEquals(stringPath, result);
}
public void testMaxCharacters() {
String stringPath = "/some/reallylongdir/is/very/annoying.txt";
PathUtil path = new PathUtil(stringPath);
String result = ClientStringUtils.ellipsisPath(path, 2, 20, SEP);
assertEquals("../very/annoying.txt", result);
assertEquals(20, result.length());
result = ClientStringUtils.ellipsisPath(path, 2, 4, SEP);
assertEquals("..xt", result);
assertEquals(4, result.length());
result = ClientStringUtils.ellipsisPath(path, 0, 2, SEP);
assertEquals(stringPath, result);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/util/BasicIncrementalSchedulerTests.java | javatests/com/google/collide/client/util/BasicIncrementalSchedulerTests.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.util;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.junit.client.GWTTestCase;
/**
* A few tests for incremental scheduler to ensure that it follows it's
* pause/resume/cancel contract. Doesn't test if the incremental portion works
* nor is this a strenous test of the component.
*/
public class BasicIncrementalSchedulerTests extends GWTTestCase {
private BasicIncrementalScheduler scheduler;
public class StubTask implements IncrementalScheduler.Task {
private boolean wasCalled = false;
@Override
public boolean run(int workAmount) {
wasCalled = true;
return false;
}
}
@Override
public void gwtSetUp() {
scheduler = new BasicIncrementalScheduler(100, 100);
}
public void testCancelDoesntUnpause() {
scheduler.pause();
scheduler.cancel();
assertTrue(scheduler.isPaused());
scheduler.resume();
assertFalse(scheduler.isPaused());
}
public void testRunsDelegate() {
scheduler.pause();
final StubTask stubTask = new StubTask();
scheduler.schedule(stubTask);
assertFalse(stubTask.wasCalled);
scheduler.resume();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
assertTrue(stubTask.wasCalled);
}
});
}
@Override
public String getModuleName() {
return "com.google.collide.client.util.UtilTestModule";
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/util/collections/ClientStringMapTest.java | javatests/com/google/collide/client/util/collections/ClientStringMapTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.util.collections;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.gwt.junit.client.GWTTestCase;
/**
* Test cases for {@link ClientStringMap}.
*/
public class ClientStringMapTest extends GWTTestCase {
private static final String[] TEST_KEYS = new String[]{
"something",
"",
"__defineGetter",
"__defineSetter__",
"__lookupGetter__",
"__lookupSetter__",
"constructor",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"toLocaleString",
"toString",
"valueOf",
"__proto__"
};
private static final class Foo {
}
@Override
public String getModuleName() {
return "com.google.collide.client.util.UtilTestModule";
}
public void testEmpty() {
ClientStringMap<Foo> map = ClientStringMap.create();
checkMapIsEmpty(map);
}
private void checkMapIsEmpty(ClientStringMap<Foo> map) {
assertTrue("emptiness", map.isEmpty());
JsoArray<String> keys = map.getKeys();
assertEquals("key list emptiness", 0, keys.size());
map.iterate(new JsonStringMap.IterationCallback<Foo>() {
@Override
public void onIteration(String key, Foo value) {
fail("iteration emptiness");
}
});
}
public void testIsEmpty() {
for (int i = 0, size = TEST_KEYS.length; i < size; i++) {
String key = TEST_KEYS[i];
ClientStringMap<Foo> map = ClientStringMap.create();
map.put(key, new Foo());
assertFalse("isEmpty with '" + key + "'", map.isEmpty());
}
}
public void testGetFromEmpty() {
for (int i = 0, size = TEST_KEYS.length; i < size; i++) {
String key = TEST_KEYS[i];
ClientStringMap<Foo> map = ClientStringMap.create();
Foo foo = map.get(key);
assertNull(".get('" + key + "') result", foo);
}
}
public void testDeleteFromEmpty() {
for (int i = 0, size = TEST_KEYS.length; i < size; i++) {
String key = TEST_KEYS[i];
ClientStringMap<Foo> map = ClientStringMap.create();
Foo foo = map.remove(key);
assertNull(".remove('" + key + "') result", foo);
checkMapIsEmpty(map);
}
}
public void testAddAndDeleteFromEmpty() {
for (int i = 0, size = TEST_KEYS.length; i < size; i++) {
String key = TEST_KEYS[i];
ClientStringMap<Foo> map = ClientStringMap.create();
Foo foo = new Foo();
map.put(key, foo);
Foo getFoo = map.get(key);
assertTrue(".get('" + key + "') result", foo == getFoo);
Foo deletedFoo = map.remove(key);
assertTrue(".remove('" + key + "') result", foo == deletedFoo);
checkMapIsEmpty(map);
}
}
public void testGetKeys() {
ClientStringMap<Foo> map = ClientStringMap.create();
Foo foo = new Foo();
for (int i = 0, size = TEST_KEYS.length; i < size; i++) {
map.put(TEST_KEYS[i], foo);
}
JsoArray<String> keys = map.getKeys();
assertEquals("number of keys", TEST_KEYS.length, keys.size());
for (int i = 0, size = TEST_KEYS.length; i < size; i++) {
String key = TEST_KEYS[i];
assertTrue("has key('" + key + "')", keys.contains(key));
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/util/collections/SkipListStringSetTest.java | javatests/com/google/collide/client/util/collections/SkipListStringSetTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.util.collections;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.client.JsoStringSet;
import com.google.collide.json.shared.JsonArray;
import com.google.gwt.junit.client.GWTTestCase;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Random;
/**
* Test cases for {@link SkipListStringSet}.
*
*/
public class SkipListStringSetTest extends GWTTestCase {
@Override
public String getModuleName() {
return "com.google.collide.client.util.UtilTestModule";
}
public void testEmpty() {
SkipListStringSet set = SkipListStringSet.create();
Iterator iterator = set.search("").iterator();
assertFalse("emptiness", iterator.hasNext());
set.remove("foo");
}
public void testAdd() {
SkipListStringSet set = SkipListStringSet.create();
set.add("foo");
Iterator iterator = set.search("foo").iterator();
assertEquals("found added element", "foo", iterator.next());
assertFalse("no more elements", iterator.hasNext());
}
public void testSearch() {
SkipListStringSet set = SkipListStringSet.create();
set.add("3");
set.add("1");
set.add("2");
Iterator iterator = set.search("2").iterator();
assertEquals("found target", "2", iterator.next());
assertEquals("found next", "3", iterator.next());
assertFalse("no more elements", iterator.hasNext());
}
public void testSearchAbsent() {
SkipListStringSet set = SkipListStringSet.create();
set.add("4");
set.add("1");
set.add("3");
Iterator iterator = set.search("2").iterator();
assertEquals("found least greater than", "3", iterator.next());
assertEquals("found next", "4", iterator.next());
assertFalse("no more elements", iterator.hasNext());
}
public void testRemove() {
SkipListStringSet set = SkipListStringSet.create();
set.add("4");
set.add("2");
set.add("1");
set.add("3");
set.remove("3");
Iterator iterator = set.search("2").iterator();
assertEquals("found target", "2", iterator.next());
assertEquals("found next", "4", iterator.next());
assertFalse("no more elements", iterator.hasNext());
}
public void testCorrectnessOnRandomData() {
Random rnd = new Random(42);
for (int i = 128; i <= 4096; i = i * 2) {
checkCorrectnessOnRandomData(rnd, i, 100);
}
checkCorrectnessOnRandomData(rnd, 16384, 10000);
}
/**
* This method is used to check correctness of implementation on random data.
*
* <p>During test random keys are generated. With some probability they are
* either added or removed form set.
*
* <p>To avoid useless operations, in situation when we were going to remove key
* that is not in set, already, we add it. Vice versa, do not add keys that are
* already in set.
*
* <p>All operations are applied to instance of target implementation and to
* instance of class that allows similar functionality (set). So resulting key
* set should be similar. This is explicitly checked.
*
* @param rnd randomness source
* @param limit number of operations to perform
* @param range how many different keys can appear in test
*/
private void checkCorrectnessOnRandomData(final Random rnd, int limit, int range) {
// Origin instance.
JsoStringSet mirror = JsoStringSet.create();
// Array to hold recently generated keys.
JsoArray<String> values = JsoArray.create();
// Target instance, with fully deterministic behavior.(driven by our
// oscillator).
SkipListStringSet target = new SkipListStringSet(8, new SkipListStringSet.LevelGenerator() {
@Override
public int generate() {
int result = 0;
while (rnd.nextInt(4) == 0 && result < 7) {
result++;
}
return result;
}
});
for (int i = 0; i < limit; i++) {
boolean remove = false;
if (values.size() > 0) {
// Actually we simulate that set is growing
// i.e. more key added than removed).
remove = rnd.nextDouble() > 0.6;
}
// Value is either generated or selected from recent values list.
String value;
if (remove) {
// When we are going to remove, recent values is a good choice
// to choose from.
value = values.get(rnd.nextInt(values.size()));
// Eventually, if can't remove - add.
if (!mirror.contains(value)) {
remove = false;
}
} else {
value = String.valueOf(rnd.nextInt(range));
// If key already in set - remove it.
if (mirror.contains(value)) {
remove = true;
} else {
values.add(value);
}
}
// Perform operation on both instances.
if (remove) {
target.remove(value);
mirror.remove(value);
} else {
target.add(value);
mirror.add(value);
}
}
// Get sorted list of set of keys.
JsonArray<String> keys = mirror.getKeys();
keys.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
// Check that keys in search result has the same order and values.
Iterator iterator = target.search(keys.get(0)).iterator();
for (int i = 0, l = keys.size(); i < l; i++) {
assertEquals("values", keys.get(i), iterator.next());
}
assertFalse("no more values", iterator.hasNext());
// Check that all keys are properly selectable.
for (int i = 0, l = keys.size(); i < l; i++) {
String value = keys.get(i);
assertEquals("search", value, target.search(value).iterator().next());
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/util/collections/ResumableTreeTraverserTest.java | javatests/com/google/collide/client/util/collections/ResumableTreeTraverserTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.util.collections;
import com.google.collide.client.ui.tree.TreeTestUtils;
import com.google.collide.client.util.collections.ResumableTreeTraverser.FinishedCallback;
import com.google.collide.client.util.collections.ResumableTreeTraverser.VisitorApi;
import com.google.collide.dto.DirInfo;
import com.google.collide.dto.FileInfo;
import com.google.collide.dto.TreeNodeInfo;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import junit.framework.TestCase;
import org.easymock.EasyMock;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/*
* The tests use a file tree since we already have a util method to create
* a nice tree. The actual data doesn't affect the traversal.
*/
/**
* Tests for {@link ResumableTreeTraverser}.
*
*/
public class ResumableTreeTraverserTest extends TestCase {
private static class NodeProvider implements ResumableTreeTraverser.NodeProvider<TreeNodeInfo> {
@Override
public Iterator<TreeNodeInfo> getChildrenIterator(TreeNodeInfo node) {
if (node instanceof FileInfo) {
return null;
}
DirInfo dirInfo = (DirInfo) node;
JsonArray<TreeNodeInfo> children = JsonCollections.createArray();
children.addAll(dirInfo.getFiles());
children.addAll(dirInfo.getSubDirectories());
return children.asIterable().iterator();
}
}
private static class Visitor implements ResumableTreeTraverser.Visitor<TreeNodeInfo> {
List<TreeNodeInfo> visitedItems = new ArrayList<TreeNodeInfo>();
@Override
public void visit(TreeNodeInfo item, VisitorApi visitorApi) {
visitedItems.add(item);
}
}
private static class AlwaysPauseVisitor extends Visitor {
@Override
public void visit(TreeNodeInfo item, VisitorApi visitorApi) {
super.visit(item, visitorApi);
visitorApi.pause();
}
}
private static class AlwaysPauseAndResumeVisitor extends Visitor {
@Override
public void visit(TreeNodeInfo item, VisitorApi visitorApi) {
super.visit(item, visitorApi);
visitorApi.pause();
visitorApi.resume();
}
}
private static class AlwaysPauseAndRemoveVisitor extends Visitor {
@Override
public void visit(TreeNodeInfo item, VisitorApi visitorApi) {
super.visit(item, visitorApi);
visitorApi.pause();
visitorApi.remove();
}
}
private static class AlwaysRemoveVisitor extends Visitor {
@Override
public void visit(TreeNodeInfo item, VisitorApi visitorApi) {
super.visit(item, visitorApi);
visitorApi.remove();
}
}
private final NodeProvider provider = new NodeProvider();
private DirInfo root;
private Visitor trivialVisitor;
public ResumableTreeTraverserTest(String name) {
super(name);
}
public void testAlwaysPauseVisitors() {
Visitor alwaysPauseVisitor = new AlwaysPauseVisitor();
Visitor alwaysPauseVisitor2 = new AlwaysPauseVisitor();
Visitor alwaysPauseVisitor3 = new AlwaysPauseVisitor();
ResumableTreeTraverser<TreeNodeInfo> traverser =
new ResumableTreeTraverser<TreeNodeInfo>(provider, provider.getChildrenIterator(root),
JsonCollections.createArray(alwaysPauseVisitor, alwaysPauseVisitor2,
alwaysPauseVisitor3), null);
// -1 to offset the first call to resume
int numPauses = -1;
while (traverser.hasMore()) {
traverser.resume();
numPauses++;
// Assert that these visitors are being called in order
assertEquals(Math.min(numPauses / 3 + 1, trivialVisitor.visitedItems.size()),
alwaysPauseVisitor.visitedItems.size());
assertEquals(
Math.min(numPauses / 3 + ((numPauses % 3 >= 1) ? 1 : 0),
trivialVisitor.visitedItems.size()), alwaysPauseVisitor2.visitedItems.size());
assertEquals(
Math.min(numPauses / 3 + ((numPauses % 3 == 2) ? 1 : 0),
trivialVisitor.visitedItems.size()), alwaysPauseVisitor3.visitedItems.size());
}
assertEquals(trivialVisitor.visitedItems, alwaysPauseVisitor.visitedItems);
assertEquals(trivialVisitor.visitedItems, alwaysPauseVisitor2.visitedItems);
assertEquals(trivialVisitor.visitedItems, alwaysPauseVisitor3.visitedItems);
assertEquals(trivialVisitor.visitedItems.size() * 3, numPauses);
}
public void testAlwaysPauseAndRemoveBlocksSubsequentVisitor() {
testVisitorWhoseRemovalBlocksSubsequentVisitor(new AlwaysPauseAndRemoveVisitor());
}
public void testAlwaysRemoveBlocksSubsequentVisitor() {
testVisitorWhoseRemovalBlocksSubsequentVisitor(new AlwaysRemoveVisitor());
}
private void testVisitorWhoseRemovalBlocksSubsequentVisitor(Visitor visitor1) {
Visitor visitor2 = new Visitor();
ResumableTreeTraverser<TreeNodeInfo> traverser =
new ResumableTreeTraverser<TreeNodeInfo>(provider, provider.getChildrenIterator(root),
JsonCollections.createArray(visitor1, visitor2), null);
while (traverser.hasMore()) {
traverser.resume();
}
// Visitor1 deletes immediately, so no children should have been visited
List<TreeNodeInfo> expectedItems = Lists.newArrayList();
Iterators.addAll(expectedItems, provider.getChildrenIterator(root));
assertEquals(expectedItems, visitor1.visitedItems);
// Since visitor1 always deletes, visitor2 should never be called
assertEquals(0, visitor2.visitedItems.size());
}
public void testVisitorBeforeAlwaysRemoveVisitor2() {
testVisitorBeforeVisitor2ThatRemoves(new Visitor(), new AlwaysRemoveVisitor());
}
public void testVisitorBeforeAlwaysPauseAndRemoveVisitor2() {
testVisitorBeforeVisitor2ThatRemoves(new Visitor(), new AlwaysPauseAndRemoveVisitor());
}
public void testAlwaysPauseVisitorBeforeAlwaysRemoveVisitor2() {
testVisitorBeforeVisitor2ThatRemoves(new AlwaysPauseVisitor(), new AlwaysRemoveVisitor());
}
public void testAlwaysPauseVisitorBeforeAlwaysPauseAndRemoveVisitor2() {
testVisitorBeforeVisitor2ThatRemoves(new AlwaysPauseVisitor(),
new AlwaysPauseAndRemoveVisitor());
}
private void testVisitorBeforeVisitor2ThatRemoves(Visitor visitor1, Visitor visitor2) {
ResumableTreeTraverser<TreeNodeInfo> traverser =
new ResumableTreeTraverser<TreeNodeInfo>(provider, provider.getChildrenIterator(root),
JsonCollections.createArray(visitor1, visitor2), null);
while (traverser.hasMore()) {
traverser.resume();
}
// Visitor2 deletes immediately, so no children should have been visited
List<TreeNodeInfo> expectedItems = Lists.newArrayList();
Iterators.addAll(expectedItems, provider.getChildrenIterator(root));
assertEquals(expectedItems, visitor1.visitedItems);
assertEquals(expectedItems, visitor2.visitedItems);
}
public void testPauseAndResumeSynchronouslyCalled() {
FinishedCallback finishedCallback =
EasyMock.createStrictMock(ResumableTreeTraverser.FinishedCallback.class);
finishedCallback.onTraversalFinished();
EasyMock.replay(finishedCallback);
ResumableTreeTraverser<TreeNodeInfo> traverser = new ResumableTreeTraverser<TreeNodeInfo>(
provider, provider.getChildrenIterator(root),
JsonCollections.createArray(new AlwaysPauseAndResumeVisitor()), finishedCallback);
while (traverser.hasMore()) {
traverser.resume();
}
EasyMock.verify(finishedCallback);
}
@Override
protected void setUp() throws Exception {
root = TreeTestUtils.createMockTree(TreeTestUtils.SERVER_NODE_INFO_FACTORY);
trivialVisitor = new Visitor();
new ResumableTreeTraverser<TreeNodeInfo>(provider, provider.getChildrenIterator(root),
JsonCollections.createArray(trivialVisitor), null).resume();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/codeunderstanding/CodeGraphTestUtils.java | javatests/com/google/collide/client/codeunderstanding/CodeGraphTestUtils.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.codeunderstanding;
import com.google.collide.client.communication.FrontendApi;
import com.google.collide.dto.CodeBlock;
import com.google.collide.dto.CodeGraphFreshness;
import com.google.collide.dto.CodeGraphRequest;
import com.google.collide.dto.CodeGraphResponse;
import com.google.collide.dto.ImportAssociation;
import com.google.collide.dto.InheritanceAssociation;
import com.google.collide.dto.TypeAssociation;
import com.google.collide.dto.client.DtoClientImpls.CodeBlockImpl;
import com.google.collide.dto.client.DtoClientImpls.CodeGraphFreshnessImpl;
import com.google.collide.dto.client.DtoClientImpls.CodeGraphImpl;
import com.google.collide.dto.client.DtoClientImpls.ImportAssociationImpl;
import com.google.collide.dto.client.DtoClientImpls.InheritanceAssociationImpl;
import com.google.collide.dto.client.DtoClientImpls.MockCodeBlockImpl;
import com.google.collide.dto.client.DtoClientImpls.MockImportAssociationImpl;
import com.google.collide.dto.client.DtoClientImpls.MockInheritanceAssociationImpl;
import com.google.collide.dto.client.DtoClientImpls.MockTypeAssociationImpl;
import com.google.collide.dto.client.DtoClientImpls.TypeAssociationImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.grok.GrokUtils;
import com.google.collide.shared.util.StringUtils;
/**
* A set of static methods / mock implementations for tests using code graph components.
*/
public class CodeGraphTestUtils {
/**
* Constructs childless {@link CodeBlockImpl} with
* specified characteristics.
*/
public static CodeBlockImpl createCodeBlock(String id, String name, CodeBlock.Type type,
int startLine, int startColumn, int endLine, int endColumn) {
return MockCodeBlockImpl.make().setId(id).setName(name)
.setBlockType(type == null ? CodeBlock.Type.VALUE_UNDEFINED : type.value)
.setStartLineNumber(startLine).setStartColumn(startColumn).setEndLineNumber(endLine)
.setEndColumn(endColumn).setChildren(JsoArray.<CodeBlock>create());
}
/**
* Constructs {@link CodeBlock} with specified characteristics and adds it
* as a child to the given block according to the given path.
*/
public static CodeBlock createCodeBlock(CodeBlock fileBlock, String id, String qname,
CodeBlock.Type type, int startLine, int startColumn, int endLine, int endColumn) {
JsonArray<String> path = StringUtils.split(qname, ".");
CodeBlock result = createCodeBlock(id, path.get(path.size() - 1), type, startLine, startColumn,
endLine, endColumn);
CodeBlock container;
if (path.size() > 1) {
JsonArray<String> parentPath = path.copy();
parentPath.remove(parentPath.size() - 1);
container = GrokUtils.getOrCreateCodeBlock(fileBlock, parentPath, GrokUtils.NO_MISSING_CHILD);
if (container == null) {
throw new RuntimeException("Can't create code block in file=" + fileBlock.getName()
+ " by qname=" + qname + ". Create all containers first");
}
} else {
container = fileBlock;
}
container.getChildren().add(result);
return result;
}
/**
* Constructs {@link CodeGraphFreshness} of specified freshness components.
*/
public static CodeGraphFreshness createFreshness(String libs, String full, String file) {
CodeGraphFreshnessImpl result = CodeGraphFreshnessImpl.make();
result.setLibsSubgraph(libs);
result.setFullGraph(full);
result.setFileTree(file);
return result;
}
/**
* Constructs {@link CodeGraphImpl} consisting given {@link CodeBlock}.
*/
public static CodeGraphImpl createCodeGraph(CodeBlock fileBlock) {
CodeGraphImpl result = CodeGraphImpl.make();
JsoStringMap<CodeBlock> codeBlocks = JsoStringMap.create();
codeBlocks.put("/foo.js", fileBlock);
result.setCodeBlockMap(codeBlocks);
return result;
}
/**
* Constructs {@link TypeAssociation} from the given source to the specified
* destination.
*/
public static TypeAssociation createTypeAssociation(CodeBlock srcFile, CodeBlock srcCodeBlock,
CodeBlock targetFile, CodeBlock targetCodeBlock) {
TypeAssociationImpl result = MockTypeAssociationImpl.make();
result.setSourceFileId(srcFile.getId()).setSourceLocalId(srcCodeBlock.getId())
.setTargetFileId(targetFile.getId()).setTargetLocalId(targetCodeBlock.getId())
.setIsRootAssociation(false);
return result;
}
/**
* Constructs {@link InheritanceAssociation} from the given source to the
* specified destination.
*/
public static InheritanceAssociation createInheritanceAssociation(CodeBlock srcFile,
CodeBlock srcCodeBlock, CodeBlock targetFile, CodeBlock targetCodeBlock) {
InheritanceAssociationImpl result = MockInheritanceAssociationImpl.make();
result.setSourceFileId(srcFile.getId()).setSourceLocalId(srcCodeBlock.getId())
.setTargetFileId(targetFile.getId()).setTargetLocalId(targetCodeBlock.getId())
.setIsRootAssociation(false);
return result;
}
public static ImportAssociation createRootImportAssociation(
CodeBlock srcFile, CodeBlock targetFile) {
ImportAssociationImpl result = MockImportAssociationImpl.make();
result.setSourceFileId(srcFile.getId()).setSourceLocalId(null)
.setTargetFileId(targetFile.getId()).setTargetLocalId(null).setIsRootAssociation(true);
return result;
}
/**
* A mock implementation of {@link CubeState.CubeResponseDistributor}.
*/
public static class MockCubeClientDistributor implements CubeState.CubeResponseDistributor {
public final JsonArray<CubeDataUpdates> collectedNotifications = JsoArray.create();
@Override
public void notifyListeners(CubeDataUpdates updates) {
collectedNotifications.add(updates);
}
}
/**
* A mock implementation of {@link FrontendApi.RequestResponseApi}.
*/
public static class MockApi
implements
FrontendApi.RequestResponseApi<CodeGraphRequest, CodeGraphResponse> {
public final JsonArray<FrontendApi.ApiCallback<CodeGraphResponse>> collectedCallbacks;
public MockApi() {
collectedCallbacks = JsoArray.create();
}
@Override
public void send(CodeGraphRequest msg, FrontendApi.ApiCallback<CodeGraphResponse> callback) {
collectedCallbacks.add(callback);
}
}
/**
* Implementation that uses {@link MockApi} and raises visibility of some
* methods.
*/
public static class MockCubeClient extends CubeClient {
public final MockApi api;
public static MockCubeClient create() {
return new MockCubeClient(new MockApi());
}
private MockCubeClient(MockApi api) {
super(api);
this.api = api;
}
@Override
public void setPath(String filePath) {
super.setPath(filePath);
}
@Override
public void cleanup() {
super.cleanup();
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/codeunderstanding/CubeStateTest.java | javatests/com/google/collide/client/codeunderstanding/CubeStateTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.codeunderstanding;
import static com.google.collide.client.codeunderstanding.CodeGraphTestUtils.MockApi;
import static com.google.collide.client.codeunderstanding.CodeGraphTestUtils.createCodeBlock;
import static com.google.collide.client.codeunderstanding.CodeGraphTestUtils.createCodeGraph;
import static com.google.collide.client.codeunderstanding.CodeGraphTestUtils.createFreshness;
import com.google.collide.client.codeunderstanding.CodeGraphTestUtils.MockCubeClientDistributor;
import com.google.collide.client.communication.FrontendApi;
import com.google.collide.dto.CodeBlock;
import com.google.collide.dto.CodeGraphResponse;
import com.google.collide.dto.client.DtoClientImpls.CodeGraphResponseImpl;
import com.google.collide.dto.client.DtoClientImpls.MockCodeGraphResponseImpl;
import com.google.collide.json.client.Jso;
import com.google.gwt.junit.client.GWTTestCase;
/**
* A test case for {@link CubeState}.
*/
public class CubeStateTest extends GWTTestCase {
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
/**
* Tests that {@link CubeState} fires update notification when it receives
* data which is more fresh than stored one.
*/
public void testFreshDataMakesUpdate() {
CodeGraphResponseImpl response = MockCodeGraphResponseImpl.make();
response.setFreshness(createFreshness("1", "0", "0"));
response.setLibsSubgraphJson(Jso.serialize(createCodeGraph(
createCodeBlock("0", "/foo.js", CodeBlock.Type.FILE, 0, 0, 1, 0))));
final MockApi api = new MockApi();
MockCubeClientDistributor distributor = new MockCubeClientDistributor();
CubeState state = new CubeState(api, distributor);
state.setFilePath("");
state.refresh();
assertEquals("no notifications after request", 0, distributor.collectedNotifications.size());
assertEquals("refresh causes one api request", 1, api.collectedCallbacks.size());
FrontendApi.ApiCallback<CodeGraphResponse> callback = api.collectedCallbacks.get(0);
assertNotNull("state pushes non null callback", callback);
callback.onMessageReceived(response);
assertEquals("just one notification on response", 1, distributor.collectedNotifications.size());
CubeDataUpdates freshness = distributor.collectedNotifications.get(0);
assertTrue("updated libs subgraph", freshness.isLibsSubgraph());
assertNotNull("has libs subgraph", state.getData().getLibsSubgraph());
assertFalse("old file tree", freshness.isFileTree());
assertFalse("old full graph", freshness.isFullGraph());
assertFalse("old workspace tree", freshness.isWorkspaceTree());
}
/**
* Tests that consequent refresh requests for the same data are collapsed to
* just one frontend request.
*/
public void testRefreshCollapsing() {
final MockApi api = new MockApi();
MockCubeClientDistributor distributor = new MockCubeClientDistributor();
CubeState state = new CubeState(api, distributor);
state.setFilePath("a.js");
state.refresh();
state.refresh();
assertEquals(1, api.collectedCallbacks.size());
}
/**
* Tests that consequent refresh requests for different data are served
* sequentially.
*/
public void testRefreshSequencing() {
CodeGraphResponseImpl response = MockCodeGraphResponseImpl.make();
response.setFreshness(createFreshness("1", "1", "1"));
final MockApi api = new MockApi();
MockCubeClientDistributor distributor = new MockCubeClientDistributor();
CubeState state = new CubeState(api, distributor);
state.setFilePath("a.js");
state.refresh();
state.setFilePath("b.js");
state.refresh();
assertEquals("one request after two refreshes", 1, api.collectedCallbacks.size());
FrontendApi.ApiCallback<CodeGraphResponse> callback = api.collectedCallbacks.get(0);
callback.onMessageReceived(response);
assertEquals("second request comes after first response", 2, api.collectedCallbacks.size());
}
/**
* Tests that consequent refresh requests for different data do not cause
* frontend request for data that is not required anymore.
*/
public void testRefreshSequencingAndCollapsing() {
CodeGraphResponseImpl response = MockCodeGraphResponseImpl.make();
response.setFreshness(createFreshness("1", "1", "1"));
final MockApi api = new MockApi();
MockCubeClientDistributor distributor = new MockCubeClientDistributor();
CubeState state = new CubeState(api, distributor);
state.setFilePath("a.js");
state.refresh();
state.setFilePath("b.js");
state.refresh();
state.setFilePath("c.js");
state.refresh();
assertEquals("first request is served immediately", 1, api.collectedCallbacks.size());
FrontendApi.ApiCallback<CodeGraphResponse> callback = api.collectedCallbacks.get(0);
callback.onMessageReceived(response);
assertEquals("second request is served after first response", 2, api.collectedCallbacks.size());
callback = api.collectedCallbacks.get(1);
callback.onMessageReceived(response);
assertEquals("no more requests after second response", 2, api.collectedCallbacks.size());
}
/**
* Tests that update notifications bring {@code false} for updates that
* doesn't bring fresh data.
*/
public void testStaleDataMakesNoUpdates() {
CodeGraphResponseImpl response = MockCodeGraphResponseImpl.make();
response.setFreshness(createFreshness("0", "0", "0"));
response.setLibsSubgraphJson(Jso.serialize(createCodeGraph(
createCodeBlock("0", "/foo.js", CodeBlock.Type.FILE, 0, 0, 1, 0))));
final MockApi api = new MockApi();
MockCubeClientDistributor distributor = new MockCubeClientDistributor();
CubeState state = new CubeState(api, distributor);
state.setFilePath("");
state.refresh();
assertEquals("no updates before response", 0, distributor.collectedNotifications.size());
assertEquals("one request for processing", 1, api.collectedCallbacks.size());
FrontendApi.ApiCallback<CodeGraphResponse> callback = api.collectedCallbacks.get(0);
assertNotNull("non null callback", callback);
callback.onMessageReceived(response);
assertEquals("one notification after response", 1, distributor.collectedNotifications.size());
CubeDataUpdates freshness = distributor.collectedNotifications.get(0);
assertFalse("old libs subgraph", freshness.isLibsSubgraph());
assertFalse("old file tree", freshness.isFileTree());
assertFalse("old full graph", freshness.isFullGraph());
assertFalse("old workspace tree", freshness.isWorkspaceTree());
assertNull("no libs subgraph", state.getData().getLibsSubgraph());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/TestUtils.java | javatests/com/google/collide/client/code/TestUtils.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code;
/**
* Shared utility code for editor tests.
*/
public class TestUtils {
/**
* This is the GWT Module used for these tests.
*/
public static final String BUILD_MODULE_NAME =
TestUtils.class.getPackage().getName() + ".TestCode";
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/DocumentCollaborationControllerTest.java | javatests/com/google/collide/client/code/DocumentCollaborationControllerTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code;
import com.google.collide.client.AppContext;
import com.google.collide.client.collaboration.DocumentCollaborationController;
import com.google.collide.client.collaboration.IncomingDocOpDemultiplexer;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.testing.BootstrappedGwtTestCase;
import com.google.collide.client.testing.MockAppContext;
import com.google.collide.dto.DocumentSelection;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.util.JsonCollections;
/**
* Tests for the {@link DocumentCollaborationController}.
*/
public class DocumentCollaborationControllerTest extends BootstrappedGwtTestCase {
AppContext context;
ParticipantModel model;
Editor editor;
@Override
public String getModuleName() {
return TestUtils.BUILD_MODULE_NAME;
}
public void testCreate() {
context = new MockAppContext();
Document document = Document.createEmpty();
IncomingDocOpDemultiplexer demux =
IncomingDocOpDemultiplexer.create(context.getMessageFilter());
DocumentCollaborationController controller = new DocumentCollaborationController(
context, model, demux, document, JsonCollections.<DocumentSelection> createArray());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/lang/LanguageHelperResolverTest.java | javatests/com/google/collide/client/code/lang/LanguageHelperResolverTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.lang;
import com.google.collide.codemirror2.SyntaxType;
import com.google.gwt.junit.client.GWTTestCase;
/**
* Test cases for {@link LanguageHelperResolver}.
*
*/
public class LanguageHelperResolverTest extends GWTTestCase {
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
public void testAllSyntaxTypesResolvable() {
SyntaxType[] types = SyntaxType.values();
for (int i = 0, l = types.length; i < l; i++) {
SyntaxType syntaxType = types[i];
try {
LanguageHelperResolver.getHelper(syntaxType);
} catch (Exception ex) {
fail("Can't obtain helper for " + syntaxType);
}
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/MockAutocompleterEnvironment.java | javatests/com/google/collide/client/code/autocomplete/MockAutocompleterEnvironment.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete;
import static com.google.collide.client.code.autocomplete.TestUtils.createDocumentParser;
import com.google.collide.client.code.autocomplete.AutocompleteProposals.ProposalWithContext;
import com.google.collide.client.code.autocomplete.TestUtils.MockIncrementalScheduler;
import com.google.collide.client.code.autocomplete.codegraph.CodeGraphAutocompleter;
import com.google.collide.client.code.autocomplete.codegraph.LimitedContextFilePrefixIndex;
import com.google.collide.client.code.autocomplete.codegraph.js.JsAutocompleter;
import com.google.collide.client.code.autocomplete.codegraph.js.JsIndexUpdater;
import com.google.collide.client.code.autocomplete.codegraph.py.PyAutocompleter;
import com.google.collide.client.code.autocomplete.codegraph.py.PyIndexUpdater;
import com.google.collide.client.code.autocomplete.css.CssAutocompleter;
import com.google.collide.client.code.autocomplete.html.HtmlAutocompleter;
import com.google.collide.client.codeunderstanding.CodeGraphTestUtils.MockCubeClient;
import com.google.collide.client.codeunderstanding.CubeClient;
import com.google.collide.client.documentparser.DocumentParser;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.testing.MockAppContext;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.util.collections.SkipListStringBag;
import com.google.collide.codemirror2.Parser;
import com.google.collide.codemirror2.SyntaxType;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.LineInfo;
/**
* Autocompleter and editor setup code.
*
* <p>This code was moved from TestSetupHelper.
*/
public class MockAutocompleterEnvironment {
/**
* Simplest implementation that remembers passed data.
*/
public static class MockAutocompleterPopup implements AutocompleteBox {
boolean isShown;
public AutocompleteProposals proposals = AutocompleteProposals.EMPTY;
public Events delegate;
@Override
public boolean isShowing() {
return isShown;
}
@Override
public boolean consumeKeySignal(SignalEventEssence signal) {
return false;
}
@Override
public void setDelegate(Events delegate) {
this.delegate = delegate;
}
@Override
public void dismiss() {
isShown = false;
}
@Override
public void positionAndShow(AutocompleteProposals items) {
isShown = true;
this.proposals = items;
}
}
/**
* {@link Autocompleter} implementation that allows to substitute given
* {@link LanguageSpecificAutocompleter}.
*/
public static class MockAutocompleter extends Autocompleter {
private LanguageSpecificAutocompleter specificAutocompleter;
public final SkipListStringBag localPrefixIndexStorage;
public final HtmlAutocompleter htmlAutocompleter;
public final CssAutocompleter cssAutocompleter;
public final CodeGraphAutocompleter jsAutocompleter;
public final CodeGraphAutocompleter pyAutocompleter;
public static MockAutocompleter create(
Editor editor, CubeClient cubeClient, AutocompleteBox popup) {
SkipListStringBag localPrefixIndexStorage = new SkipListStringBag();
LimitedContextFilePrefixIndex contextFilePrefixIndex = new LimitedContextFilePrefixIndex(
10, localPrefixIndexStorage);
CssAutocompleter cssAutocompleter = CssAutocompleter.create();
CodeGraphAutocompleter jsAutocompleter = JsAutocompleter.create(
cubeClient, contextFilePrefixIndex);
HtmlAutocompleter htmlAutocompleter = HtmlAutocompleter.create(
cssAutocompleter, jsAutocompleter);
CodeGraphAutocompleter pyAutocompleter = PyAutocompleter.create(
cubeClient, contextFilePrefixIndex);
return new MockAutocompleter(editor, popup, localPrefixIndexStorage, htmlAutocompleter,
cssAutocompleter, jsAutocompleter, pyAutocompleter);
}
MockAutocompleter(Editor editor, final AutocompleteBox popup,
SkipListStringBag localPrefixIndexStorage, HtmlAutocompleter htmlAutocompleter,
CssAutocompleter cssAutocompleter, CodeGraphAutocompleter jsAutocompleter,
CodeGraphAutocompleter pyAutocompleter) {
super(editor, popup, localPrefixIndexStorage, htmlAutocompleter, cssAutocompleter,
jsAutocompleter, pyAutocompleter, new PyIndexUpdater(), new JsIndexUpdater());
this.localPrefixIndexStorage = localPrefixIndexStorage;
this.htmlAutocompleter = htmlAutocompleter;
this.cssAutocompleter = cssAutocompleter;
this.jsAutocompleter = jsAutocompleter;
this.pyAutocompleter = pyAutocompleter;
}
@Override
protected LanguageSpecificAutocompleter getAutocompleter(SyntaxType mode) {
if (specificAutocompleter != null && SyntaxType.NONE == mode) {
return specificAutocompleter;
}
return super.getAutocompleter(mode);
}
@Override
public void reallyFinishAutocompletion(ProposalWithContext proposal) {
super.reallyFinishAutocompletion(proposal);
}
public boolean pressKey(SignalEventEssence key) {
return processKeyPress(key);
}
public void requestAutocomplete() {
super.requestAutocomplete(getController(), null);
}
}
public MockAutocompleter autocompleter;
public Editor editor;
public final MockCubeClient cubeClient = MockCubeClient.create();
public LanguageSpecificAutocompleter specificAutocompleter;
public Parser specificParser;
public MockAutocompleterPopup popup;
public DocumentParser parser;
public MockIncrementalScheduler parseScheduler = new MockIncrementalScheduler();
public MockAutocompleter setup(PathUtil path, String text, int lineNumber, int column,
boolean setupRealParser) {
return setup(path, Document.createFromString(text), lineNumber, column, setupRealParser);
}
public MockAutocompleter setup(PathUtil path, Document document, int lineNumber, int column,
boolean setupRealParser) {
editor = Editor.create(new MockAppContext());
editor.setDocument(document);
popup = new MockAutocompleterPopup();
autocompleter = MockAutocompleter.create(editor, cubeClient, popup);
autocompleter.specificAutocompleter = specificAutocompleter;
if (specificParser == null) {
parser = createDocumentParser(path, setupRealParser, parseScheduler, document);
} else {
parser = DocumentParser.create(document, specificParser, parseScheduler);
}
autocompleter.reset(path, parser);
LineInfo lineInfo = editor.getDocument().getLineFinder().findLine(lineNumber);
editor.getSelection().setSelection(lineInfo, column, lineInfo, column);
return autocompleter;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/AutocompleterTest.java | javatests/com/google/collide/client/code/autocomplete/AutocompleterTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete;
import static com.google.collide.client.code.autocomplete.TestUtils.createDocumentParser;
import com.google.collide.client.code.autocomplete.AutocompleteProposals.ProposalWithContext;
import com.google.collide.client.code.autocomplete.AutocompleteResult.PopupAction;
import com.google.collide.client.code.autocomplete.MockAutocompleterEnvironment.MockAutocompleter;
import com.google.collide.client.code.autocomplete.codegraph.CodeGraphAutocompleter;
import com.google.collide.client.code.autocomplete.css.CssAutocompleter;
import com.google.collide.client.code.autocomplete.html.HtmlAutocompleter;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.editor.selection.SelectionModel;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.collide.client.util.PathUtil;
import com.google.collide.codemirror2.SyntaxType;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.LineInfo;
import com.google.collide.shared.util.JsonCollections;
/**
* Test for some aspects of autocompletion life cycle.
*
*/
public class AutocompleterTest extends SynchronousTestCase {
private static class StubAutocompleter extends NoneAutocompleter {
public StubAutocompleter() {
super(SyntaxType.HTML);
}
@Override
public AutocompleteProposals findAutocompletions(SelectionModel selection,
SignalEventEssence trigger) {
return new AutocompleteProposals(SyntaxType.NONE, "",
JsonCollections.createArray(new AutocompleteProposal("ab")));
}
@Override
public AutocompleteResult computeAutocompletionResult(
ProposalWithContext proposal) {
return new DefaultAutocompleteResult("ab", 2, 0, 0, 0, PopupAction.CLOSE, "a");
}
}
private MockAutocompleterEnvironment helper;
private PathUtil path;
@Override
public String getModuleName() {
return
"com.google.collide.client.TestCode";
}
@Override
public void gwtSetUp() throws Exception {
super.gwtSetUp();
helper = new MockAutocompleterEnvironment();
path = new PathUtil("/test.none");
}
private static void changeAutocompleterPath(Autocompleter autocompleter, PathUtil path) {
autocompleter.reset(path, createDocumentParser(path));
}
public void testAutocompleteControllerLifecycleImplicitOnDocEvent() {
helper.specificAutocompleter = new StubAutocompleter();
Autocompleter autocompleter = helper.setup(path, "<a", 0, 2, false);
assertNotNull(autocompleter.getController());
autocompleter.requestAutocomplete(autocompleter.getController(), null);
assertNotNull(autocompleter.getController());
autocompleter.dismissAutocompleteBox();
assertNotNull(autocompleter.getController());
}
public void testDismissAutocompleteBox() {
helper.specificAutocompleter = new StubAutocompleter();
MockAutocompleter autocompleter = helper.setup(path, "a", 0, 1, false);
autocompleter.requestAutocomplete(autocompleter.getController(), null);
assertTrue("expected: popup appeared", helper.popup.isShowing());
autocompleter.dismissAutocompleteBox();
assertFalse("expected: popup disappeared", helper.popup.isShowing());
}
public void testDoAutocomplete() {
helper.specificAutocompleter = new StubAutocompleter();
MockAutocompleter autocompleter = helper.setup(path, "a", 0, 1, false);
autocompleter.requestAutocomplete(autocompleter.getController(), null);
assertTrue("expected: popup appeared", helper.popup.isShowing());
assertEquals("expected: 1 proposal found", 1, helper.popup.proposals.size());
}
public void testEditorContentsReplaced() {
Autocompleter autocompleter = helper.setup(path, "", 0, 0, false);
changeAutocompleterPath(autocompleter, new PathUtil("/test.html"));
assertEquals(SyntaxType.HTML, autocompleter.getMode());
changeAutocompleterPath(autocompleter, new PathUtil("/test.js"));
assertEquals(SyntaxType.JS, autocompleter.getMode());
changeAutocompleterPath(autocompleter, new PathUtil("/test.py"));
assertEquals(SyntaxType.PY, autocompleter.getMode());
changeAutocompleterPath(autocompleter, new PathUtil("/test.css"));
assertEquals(SyntaxType.CSS, autocompleter.getMode());
changeAutocompleterPath(autocompleter, new PathUtil("/test.foo"));
assertEquals(SyntaxType.NONE, autocompleter.getMode());
changeAutocompleterPath(autocompleter, new PathUtil(""));
assertEquals(SyntaxType.NONE, autocompleter.getMode());
}
public void testFinishAutocompletion() {
helper.specificAutocompleter = new StubAutocompleter();
MockAutocompleter autocompleter = helper.setup(path, "a", 0, 1, false);
AutocompleteController controller = autocompleter.getController();
assertNotNull(controller);
autocompleter.requestAutocomplete(controller, null);
autocompleter.reallyFinishAutocompletion(helper.popup.proposals.select(0));
assertEquals("ab", helper.editor.getDocument().asText());
// check that the caret is in the right place
assertEquals(2, helper.editor.getSelection().getCursorColumn());
assertNotNull(autocompleter.getController());
}
public void testProposalsUpdate() {
helper.specificAutocompleter = new StubAutocompleter();
Autocompleter autocompleter = helper.setup(path, "a", 0, 1, false);
AutocompleteController controller = autocompleter.getController();
autocompleter.requestAutocomplete(controller, null);
// Requesting completions again
controller.start(helper.editor.getSelection(), null);
assertEquals(1, helper.popup.proposals.size());
}
public void testProposalsSorting() {
JsonArray<AutocompleteProposal> unsortedCompletions = JsonCollections.createArray();
unsortedCompletions.add(new AutocompleteProposal("ur"));
unsortedCompletions.add(new AutocompleteProposal("go"));
unsortedCompletions.add(new AutocompleteProposal("Gb"));
unsortedCompletions.add(new AutocompleteProposal("ga"));
unsortedCompletions.add(new AutocompleteProposal("ab"));
unsortedCompletions.add(new AutocompleteProposal("gA"));
unsortedCompletions.add(new AutocompleteProposal("go"));
AutocompleteProposals proposals =
new AutocompleteProposals(SyntaxType.NONE, "", unsortedCompletions);
assertEquals("input/output size", unsortedCompletions.size(), proposals.size());
String previous = proposals.get(0).getLabel();
for (int i = 1, l = proposals.size(); i < l; i++) {
String current = proposals.get(i).getLabel();
assertTrue("order", current.compareToIgnoreCase(previous) >= 0);
previous = current;
}
}
public void testAutocompletionMode() {
Autocompleter autocompleter = helper.setup(path, "", 0, 0, false);
SyntaxType mode = SyntaxType.NONE;
assertTrue(autocompleter.getAutocompleter(mode) instanceof NoneAutocompleter);
mode = SyntaxType.YAML;
assertTrue(autocompleter.getAutocompleter(mode) instanceof NoneAutocompleter);
mode = SyntaxType.SVG;
assertTrue(autocompleter.getAutocompleter(mode) instanceof NoneAutocompleter);
mode = SyntaxType.XML;
assertTrue(autocompleter.getAutocompleter(mode) instanceof NoneAutocompleter);
mode = SyntaxType.CSS;
assertTrue(autocompleter.getAutocompleter(mode) instanceof CssAutocompleter);
mode = SyntaxType.HTML;
assertTrue(autocompleter.getAutocompleter(mode) instanceof HtmlAutocompleter);
mode = SyntaxType.JS;
LanguageSpecificAutocompleter jsAutocompleter = autocompleter.getAutocompleter(mode);
assertTrue(jsAutocompleter instanceof CodeGraphAutocompleter);
assertEquals(mode, jsAutocompleter.getMode());
}
public void testAutocompletionDoNotBreakAppOnSelectedText() {
helper.specificAutocompleter = new LanguageSpecificAutocompleter(SyntaxType.HTML) {
@Override
public AutocompleteResult computeAutocompletionResult(ProposalWithContext proposal) {
return new DefaultAutocompleteResult("[]", 1, 0, 0, 0, PopupAction.CLOSE, "");
}
@Override
public AutocompleteProposals findAutocompletions(
SelectionModel selection, SignalEventEssence trigger) {
return AutocompleteProposals.EMPTY;
}
@Override
public void cleanup() {}
};
// Forward selection
Autocompleter autocompleter = helper.setup(path, "go (veryLongSelection).q!", 0, 0, false);
Editor editor = helper.editor;
LineInfo lineInfo = editor.getDocument().getLineFinder().findLine(0);
editor.getSelection().setSelection(lineInfo, 4, lineInfo, 21);
ProposalWithContext proposal = new ProposalWithContext(SyntaxType.NONE,
new AutocompleteProposal(""), new AutocompleteProposals.Context(""));
autocompleter.reallyFinishAutocompletion(proposal);
assertEquals("go ([]).q!", editor.getDocument().getFirstLine().getText());
assertFalse(editor.getSelection().hasSelection());
assertEquals(5, editor.getSelection().getCursorPosition().getColumn());
// Reverse selection
autocompleter = helper.setup(path, "go (veryLongSelection).q!", 0, 0, false);
editor = helper.editor;
lineInfo = editor.getDocument().getLineFinder().findLine(0);
editor.getSelection().setSelection(lineInfo, 21, lineInfo, 4);
autocompleter.reallyFinishAutocompletion(proposal);
assertEquals("go ([]).q!", editor.getDocument().getFirstLine().getText());
assertFalse(editor.getSelection().hasSelection());
assertEquals(5, editor.getSelection().getCursorPosition().getColumn());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/TestUtils.java | javatests/com/google/collide/client/code/autocomplete/TestUtils.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete;
import static org.waveprotocol.wave.client.common.util.SignalEvent.KeySignalType.INPUT;
import com.google.collide.client.code.autocomplete.AutocompleteProposals.ProposalWithContext;
import com.google.collide.client.documentparser.DocumentParser;
import com.google.collide.client.util.IncrementalScheduler;
import com.google.collide.client.util.PathUtil;
import com.google.collide.codemirror2.CodeMirror2;
import com.google.collide.codemirror2.Parser;
import com.google.collide.codemirror2.State;
import com.google.collide.codemirror2.Stream;
import com.google.collide.codemirror2.SyntaxType;
import com.google.collide.codemirror2.Token;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringSet;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.util.JsonCollections;
/**
* A set of common test utilities and mock implementations.
*
* <p>This code was moved from TestSetupHelper.
*/
public class TestUtils {
public static final SignalEventEssence CTRL_SPACE = new SignalEventEssence(
' ', true, false, false, false, INPUT);
public static final SignalEventEssence CTRL_SHIFT_SPACE = new SignalEventEssence(
' ', true, false, true, false, INPUT);
/**
* Implementation that publishes its content.
*/
public static class MockStream implements Stream {
/**
* Flag that indicates "at the end of line".
*
* <p>This flag is toggled each time {@link #isEnd} is called. That way the
* first invocation of {@link #isEnd} always returns {@code false} and
* second invocation returns {@code true}.
*
* <p>Described behavior allows {@link MockParser} implementations to push
* tokens. To determine what tokens to push, {@link #getText} can be used.
*/
boolean toggle = true;
private final String text;
public MockStream(String text) {
this.text = text;
}
public String getText() {
return text;
}
/**
* @see #toggle
*/
@Override
public boolean isEnd() {
toggle = !toggle;
return toggle;
}
}
/**
* Implementation that "collects" schedule requests.
*/
public static class MockIncrementalScheduler implements IncrementalScheduler {
public final JsonArray<Task> requests = JsonCollections.createArray();
@Override
public void schedule(Task worker) {
requests.add(worker);
}
@Override
public void cancel() {
requests.clear();
}
@Override
public void pause() {}
@Override
public void resume() {}
@Override
public boolean isPaused() {
return false;
}
@Override
public boolean isBusy() {
return !requests.isEmpty();
}
@Override
public void teardown() {}
}
private static class MockState implements State {
@Override
public State copy(Parser codeMirrorParser) {
return createMockState();
}
}
/**
* Mock {@link Parser} implementation.
*/
public static class MockParser implements Parser {
private final SyntaxType type;
public MockParser(SyntaxType type) {
this.type = type;
}
@Override
public boolean hasSmartIndent() {
return false;
}
@Override
public SyntaxType getSyntaxType() {
return type;
}
@Override
public int indent(State stateBefore, String textAfter) {
return 0;
}
@Override
public State defaultState() {
return createMockState();
}
@Override
public void parseNext(Stream stream, State parserState, JsonArray<Token> tokens) {
}
@Override
public Stream createStream(String text) {
return new MockStream(text);
}
@Override
public String getName(State state) {
return type.getName();
}
}
public static <T extends AutocompleteProposal> JsonStringSet createNameSet(
JsonArray<T> proposals) {
JsonStringSet result = JsonCollections.createStringSet();
for (int i = 0; i < proposals.size(); i++) {
result.add(proposals.get(i).name);
}
return result;
}
public static JsonStringSet createNameSet(AutocompleteProposals proposals) {
JsonStringSet result = JsonCollections.createStringSet();
for (int i = 0; i < proposals.size(); i++) {
result.add(proposals.get(i).name);
}
return result;
}
public static AbstractTrie<String> createStringTrie(String... items) {
AbstractTrie<String> result = new AbstractTrie<String>();
for (String item : items) {
result.put(item, item);
}
return result;
}
public static <T extends AutocompleteProposal> String joinNames(JsonArray<T> proposals) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < proposals.size(); i++) {
if (i > 0) {
result.append(",");
}
result.append(proposals.get(i).name);
}
return result.toString();
}
public static <T extends AutocompleteProposal> T findProposalByName(
JsonArray<T> proposals, String name) {
for (int i = 0; i < proposals.size(); i++) {
if (proposals.get(i).getName().equals(name)) {
return proposals.get(i);
}
}
return null;
}
public static State createMockState() {
return new MockState();
}
public static DocumentParser createDocumentParser(PathUtil path) {
return createDocumentParser(
path, false, new MockIncrementalScheduler(), Document.createEmpty());
}
public static DocumentParser createDocumentParser(PathUtil path, boolean setupRealParser,
IncrementalScheduler scheduler, Document document) {
Parser parser = setupRealParser ? CodeMirror2.getParser(path)
: new MockParser(SyntaxType.syntaxTypeByFilePath(path));
return DocumentParser.create(document, parser, scheduler);
}
/**
* Selects and returns proposal with given name.
*
* @return {@code null} if proposal with specified name is not found
*/
public static ProposalWithContext selectProposalByName(
AutocompleteProposals proposals, String name) {
for (int i = 0, n = proposals.size(); i < n; i++) {
AutocompleteProposal proposal = proposals.get(i);
if (proposal.getName().equals(name)) {
return proposals.select(i);
}
}
return null;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/AbstractTrieTest.java | javatests/com/google/collide/client/code/autocomplete/AbstractTrieTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete;
import com.google.collide.client.testutil.SynchronousTestCase;
/**
* Test cases for {@link AbstractTrie}.
*/
public class AbstractTrieTest extends SynchronousTestCase {
AbstractTrie<String> trie;
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
@Override
public void gwtSetUp() throws Exception {
super.gwtSetUp();
trie = TestUtils.createStringTrie("a", "ab", "ac");
}
public void testDuplicates() {
trie = TestUtils.createStringTrie("abc", "def", "abc");
assertEquals("abc,def", AbstractTrie.collectSubtree(trie.getRoot()).join(","));
assertEquals("abc", trie.search("ab").join(","));
}
public void testfindAutocompletions() {
assertEquals("a,ab,ac", trie.search("").join(","));
assertEquals("ac", trie.search("ac").join(""));
assertEquals(0, trie.search("b").size());
}
public void testfindNode() {
TrieNode<String> node = AbstractTrie.findNode("", trie.getRoot());
assertEquals(trie.getRoot(), node);
node = AbstractTrie.findNode("a", trie.getRoot());
assertEquals("a", node.getPrefix());
node = AbstractTrie.findNode("b", trie.getRoot());
assertNull(node);
}
public void testGetAllLeavesInSubtree() {
assertEquals("a,ab,ac", AbstractTrie.collectSubtree(trie.getRoot()).join(","));
}
public void testInsertIntoTrie() {
trie.put("foo", "foo");
assertNotNull(AbstractTrie.findNode("foo", trie.getRoot()));
}
public void testTrieSetup() {
assertEquals("", trie.getRoot().getPrefix());
}
public void testPopulateTrie() {
trie = TestUtils.createStringTrie("a.b", "a.c", "a.b.c");
assertNotNull(AbstractTrie.findNode("a.b", trie.getRoot()));
assertNotNull(AbstractTrie.findNode("a.c", trie.getRoot()));
assertNotNull(AbstractTrie.findNode("a.b.c", trie.getRoot()));
}
public void testFindAutocompletions() {
trie = TestUtils.createStringTrie("a.b", "a.c", "a.b.c");
assertEquals("a.b.c", trie.search("a.b.").join(""));
}
public void testCL21928774() {
// Prior to CL 21928774 this test would fail with ClassCastException
trie = new AbstractTrie<String>();
trie.put("__proto__", "__proto__");
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/TrieNodeTest.java | javatests/com/google/collide/client/code/autocomplete/TrieNodeTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete;
import com.google.collide.client.testutil.SynchronousTestCase;
/**
*
*/
public class TrieNodeTest extends SynchronousTestCase {
TrieNode trieNode;
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
@Override
public void gwtSetUp() throws Exception {
super.gwtSetUp();
trieNode = TrieNode.makeNode("foo");
}
public void testGetChildren() {
assertEquals(0, trieNode.getChildren().size());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/integration/AutocompleteUiControllerTest.java | javatests/com/google/collide/client/code/autocomplete/integration/AutocompleteUiControllerTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.integration;
import com.google.collide.client.code.autocomplete.AutocompleteProposal;
import com.google.collide.client.code.autocomplete.AutocompleteProposals;
import com.google.collide.client.code.autocomplete.integration.AutocompleteUiController.Resources;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.testing.MockAppContext;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.collide.codemirror2.SyntaxType;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.util.JsonCollections;
import com.google.gwt.core.client.GWT;
/**
* Tests for AutocompleteComponent.
*/
public class AutocompleteUiControllerTest extends SynchronousTestCase {
@Override
public String getModuleName() {
return
"com.google.collide.client.TestCode";
}
public void testSetItems() {
Editor editor = Editor.create(new MockAppContext());
editor.setDocument(Document.createFromString(""));
AutocompleteUiController box = new AutocompleteUiController(
editor, (Resources) GWT.create(Resources.class));
JsonArray<AutocompleteProposal> items = JsonCollections.createArray();
items.add(new AutocompleteProposal("First"));
items.add(new AutocompleteProposal("Second"));
items.add(new AutocompleteProposal("Third"));
AutocompleteProposals proposals = new AutocompleteProposals(SyntaxType.NONE, "", items);
box.positionAndShow(proposals);
assertEquals(3, box.getList().size());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/codemirror/PyIndexUpdaterTest.java | javatests/com/google/collide/client/code/autocomplete/codemirror/PyIndexUpdaterTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.codemirror;
import com.google.collide.client.code.autocomplete.MockAutocompleterEnvironment;
import com.google.collide.client.code.autocomplete.codegraph.py.PyCodeScope;
import com.google.collide.client.code.autocomplete.codegraph.py.PyIndexUpdater;
import com.google.collide.client.code.autocomplete.integration.TaggableLineUtil;
import com.google.collide.client.documentparser.DocumentParser;
import com.google.collide.client.testutil.CodeMirrorTestCase;
import com.google.collide.client.util.PathUtil;
import com.google.collide.codemirror2.Token;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.TaggableLine;
import com.google.collide.shared.document.Line;
import javax.annotation.Nonnull;
/**
* Test for {@link PyIndexUpdater}.
*/
public class PyIndexUpdaterTest extends CodeMirrorTestCase {
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
public void testScopes() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
String text = ""
+ "# Comment\n"
+ "class Foo:\n"
+ " \"Foo is very clever and open-minded\"\n"
+ " def goo(self, dwarf):\n"
+ " whatever = [\n"
+ "\"whenever\"\n"
+ " ]\n"
+ " # Fais ce que dois, advienne que pourra\n"
+ "\n"
+ " def roo(gnome):\n"
+ " self.this = def class\n"
+ " # La culture, c'est ce qui reste quand on a tout oublié.\n"
+ "class Bar:\n"
// Also test that different indention scheme works well.
+ " \"Bar is a unit of pressure, roughly equal to the atmospheric pressure on Earth\"\n"
+ " def far(self):\n"
+ " The kingdom of FAR FAR Away, Donkey? That's where we're going! FAR! FAR!... away.\n";
helper.setup(new PathUtil("foo.py"), text, 0, 0, true);
final PyIndexUpdater analyzer = new PyIndexUpdater();
helper.parser.getListenerRegistrar().add(new DocumentParser.Listener() {
private boolean asyncParsing;
@Override
public void onIterationStart(int lineNumber) {
asyncParsing = true;
analyzer.onBeforeParse();
}
@Override
public void onIterationFinish() {
asyncParsing = false;
analyzer.onAfterParse();
}
@Override
public void onDocumentLineParsed(
Line line, int lineNumber, @Nonnull JsonArray<Token> tokens) {
if (asyncParsing) {
TaggableLine previousLine = TaggableLineUtil.getPreviousLine(line);
analyzer.onParseLine(previousLine, line, tokens);
}
}
});
helper.parser.begin();
helper.parseScheduler.requests.get(0).run(20);
//# Comment
Line line = helper.editor.getDocument().getFirstLine();
PyCodeScope scope = line.getTag(PyIndexUpdater.TAG_SCOPE);
assertNull(scope);
//class Foo:
line = line.getNextLine();
scope = line.getTag(PyIndexUpdater.TAG_SCOPE);
assertNotNull(scope);
assertEquals(PyCodeScope.Type.CLASS, scope.getType());
assertEquals("Foo", PyCodeScope.buildPrefix(scope).join("#"));
PyCodeScope prevScope = scope;
// "Foo is very clever and open-minded"
line = line.getNextLine();
scope = line.getTag(PyIndexUpdater.TAG_SCOPE);
assertTrue(scope == prevScope);
// def goo(self, dwarf):
line = line.getNextLine();
scope = line.getTag(PyIndexUpdater.TAG_SCOPE);
assertNotNull(scope);
assertEquals(PyCodeScope.Type.DEF, scope.getType());
assertEquals("Foo#goo", PyCodeScope.buildPrefix(scope).join("#"));
prevScope = scope;
// whatever = [
line = line.getNextLine();
scope = line.getTag(PyIndexUpdater.TAG_SCOPE);
assertTrue(scope == prevScope);
//"whenever"
line = line.getNextLine();
scope = line.getTag(PyIndexUpdater.TAG_SCOPE);
assertTrue(scope == prevScope);
// ]
line = line.getNextLine();
scope = line.getTag(PyIndexUpdater.TAG_SCOPE);
assertTrue(scope == prevScope);
// # Fais ce que dois, advienne que pourra
line = line.getNextLine();
scope = line.getTag(PyIndexUpdater.TAG_SCOPE);
assertTrue(scope == prevScope);
//
line = line.getNextLine();
scope = line.getTag(PyIndexUpdater.TAG_SCOPE);
assertTrue(scope == prevScope);
// def roo(gnome):
line = line.getNextLine();
scope = line.getTag(PyIndexUpdater.TAG_SCOPE);
assertNotNull(scope);
assertEquals(PyCodeScope.Type.DEF, scope.getType());
assertEquals("Foo#roo", PyCodeScope.buildPrefix(scope).join("#"));
prevScope = scope;
// self.this = def class
line = line.getNextLine();
scope = line.getTag(PyIndexUpdater.TAG_SCOPE);
assertTrue(scope == prevScope);
// # La culture, c'est ce qui reste quand on a tout oublié.
line = line.getNextLine();
scope = line.getTag(PyIndexUpdater.TAG_SCOPE);
assertTrue(scope == prevScope);
//class Bar:
line = line.getNextLine();
scope = line.getTag(PyIndexUpdater.TAG_SCOPE);
assertNotNull(scope);
assertEquals(PyCodeScope.Type.CLASS, scope.getType());
assertEquals("Bar", PyCodeScope.buildPrefix(scope).join("#"));
prevScope = scope;
// "Bar is a unit of pressure, roughly equal to the atmospheric pressure on Earth"
line = line.getNextLine();
scope = line.getTag(PyIndexUpdater.TAG_SCOPE);
assertTrue(scope == prevScope);
// def far(self):
line = line.getNextLine();
scope = line.getTag(PyIndexUpdater.TAG_SCOPE);
assertNotNull(scope);
assertEquals(PyCodeScope.Type.DEF, scope.getType());
assertEquals("Bar#far", PyCodeScope.buildPrefix(scope).join("#"));
prevScope = scope;
// The kingdom of FAR FAR Away, Donkey? That's where we're going! FAR! FAR!... away.
line = line.getNextLine();
scope = line.getTag(PyIndexUpdater.TAG_SCOPE);
assertTrue(scope == prevScope);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/codemirror/CaseInsensitiveTest.java | javatests/com/google/collide/client/code/autocomplete/codemirror/CaseInsensitiveTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.codemirror;
import static com.google.collide.client.code.autocomplete.TestUtils.CTRL_SPACE;
import com.google.collide.client.code.autocomplete.AutocompleteProposals;
import com.google.collide.client.code.autocomplete.Autocompleter;
import com.google.collide.client.code.autocomplete.MockAutocompleterEnvironment;
import com.google.collide.client.code.autocomplete.TestUtils;
import com.google.collide.client.testutil.CodeMirrorTestCase;
import com.google.collide.client.util.PathUtil;
import com.google.collide.shared.document.Line;
/**
* Test cases that check case-insensitiveness of autocompleter.
*/
public class CaseInsensitiveTest extends CodeMirrorTestCase {
@Override
public void gwtSetUp() throws Exception {
super.gwtSetUp();
assertTrue(Autocompleter.CASE_INSENSITIVE);
}
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
public void testTemplate() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("foo.js"), "WhI", 0, 3, true);
AutocompleteProposals proposals = helper.autocompleter.jsAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
AutocompleteProposals.ProposalWithContext proposal = TestUtils.selectProposalByName(
proposals, "while");
assertNotNull(proposal);
helper.autocompleter.reallyFinishAutocompletion(proposal);
assertEquals("while () {\n", helper.editor.getDocument().getFirstLine().getText());
}
public void testLocalVariable() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
String text = "function foo() {\n"
+ " var barBeQue;\n"
+ " BArbE\n" // Cursor here.
+ "}";
helper.setup(new PathUtil("foo.js"), text, 2, 7, true);
helper.parser.begin();
helper.parseScheduler.requests.get(0).run(10);
AutocompleteProposals proposals = helper.autocompleter.jsAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
AutocompleteProposals.ProposalWithContext proposal = TestUtils.selectProposalByName(
proposals, "barBeQue");
assertNotNull(proposal);
helper.autocompleter.reallyFinishAutocompletion(proposal);
Line thirdLine = helper.editor.getDocument().getLineFinder().findLine(2).line();
assertEquals(" barBeQue\n", thirdLine.getText());
}
public void testCssProperty() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
String prefix = "td {bORDEr: black; ";
helper.setup(new PathUtil("foo.css"), prefix + "boR", 0, prefix.length() + 3, true);
AutocompleteProposals proposals = helper.autocompleter.cssAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
assertNull(TestUtils.selectProposalByName(proposals, "border"));
AutocompleteProposals.ProposalWithContext proposal = TestUtils.selectProposalByName(
proposals, "border-color");
assertNotNull(proposal);
helper.autocompleter.reallyFinishAutocompletion(proposal);
String text = helper.editor.getDocument().getFirstLine().getText();
assertTrue(text.startsWith(prefix + "border-color"));
}
public void testCssValue() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
String prefix = "td {color: ";
helper.setup(new PathUtil("foo.css"), prefix + "BLA", 0, prefix.length() + 3, true);
AutocompleteProposals proposals = helper.autocompleter.cssAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
AutocompleteProposals.ProposalWithContext proposal = TestUtils.selectProposalByName(
proposals, "black");
assertNotNull(proposal);
helper.autocompleter.reallyFinishAutocompletion(proposal);
String text = helper.editor.getDocument().getFirstLine().getText();
assertTrue(text.startsWith(prefix + "black"));
}
public void testHtmlAttributes() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
String prefix = "<html iD='' ";
helper.setup(new PathUtil("foo.html"), prefix + "I", 0, prefix.length() + 1, true);
helper.parser.begin();
helper.parseScheduler.requests.get(0).run(10);
AutocompleteProposals proposals = helper.autocompleter.htmlAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
assertNull(TestUtils.selectProposalByName(proposals, "id"));
AutocompleteProposals.ProposalWithContext proposal = TestUtils.selectProposalByName(
proposals, "itemid");
assertNotNull(proposal);
helper.autocompleter.reallyFinishAutocompletion(proposal);
String text = helper.editor.getDocument().getFirstLine().getText();
assertTrue(text.startsWith(prefix + "itemid"));
}
public void testHtmlPreviousLineAttributes() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
String prefix = "<html iD='' \n";
helper.setup(new PathUtil("foo.html"), prefix + "I", 1, 1, true);
helper.parser.begin();
helper.parseScheduler.requests.get(0).run(10);
AutocompleteProposals proposals = helper.autocompleter.htmlAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
assertNull(TestUtils.selectProposalByName(proposals, "id"));
}
public void testHtmlTag() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("foo.html"), "<HT", 0, 3, true);
helper.parser.begin();
helper.parseScheduler.requests.get(0).run(10);
AutocompleteProposals proposals = helper.autocompleter.htmlAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
AutocompleteProposals.ProposalWithContext proposal = TestUtils.selectProposalByName(
proposals, "html");
assertNotNull(proposal);
helper.autocompleter.reallyFinishAutocompletion(proposal);
String text = helper.editor.getDocument().getFirstLine().getText();
assertTrue(text.startsWith("<html"));
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/codemirror/CssCodemirrorTest.java | javatests/com/google/collide/client/code/autocomplete/codemirror/CssCodemirrorTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.codemirror;
import com.google.collide.client.code.autocomplete.AutocompleteResult;
import com.google.collide.client.code.autocomplete.DefaultAutocompleteResult;
import com.google.collide.client.code.autocomplete.LanguageSpecificAutocompleter.ExplicitAction;
import com.google.collide.client.code.autocomplete.LanguageSpecificAutocompleter.ExplicitActionType;
import com.google.collide.client.code.autocomplete.MockAutocompleterEnvironment;
import com.google.collide.client.code.autocomplete.SignalEventEssence;
import com.google.collide.client.documentparser.DocumentParser;
import com.google.collide.client.testutil.TestSchedulerImpl;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.workspace.outline.CssOutlineParser;
import com.google.collide.client.workspace.outline.OutlineConsumer;
import com.google.collide.client.workspace.outline.OutlineNode;
import com.google.collide.codemirror2.Token;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringSet;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.ListenerManager;
import com.google.gwt.core.client.Scheduler;
import org.waveprotocol.wave.client.common.util.SignalEvent.KeySignalType;
import javax.annotation.Nullable;
/**
* Test for explicit autocompletion cases, when codemirror parser is used.
*
*/
public class CssCodemirrorTest extends
com.google.collide.client.testutil.CodeMirrorTestCase {
private static final String EXPLICIT_BRACES = "{\n \n}";
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
private void checkExplicit(@Nullable String expected, String prefix) {
SignalEventEssence trigger = new SignalEventEssence('{');
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("foo.css"), prefix, 0, prefix.length(), true);
ExplicitAction action = helper.autocompleter.cssAutocompleter.getExplicitAction(
helper.editor.getSelection(), trigger, false);
AutocompleteResult commonResult = action.getExplicitAutocompletion();
if (expected == null) {
assertNull("result", commonResult);
assertFalse("action", ExplicitActionType.EXPLICIT_COMPLETE == action.getType());
return;
} else {
assertTrue("action", ExplicitActionType.EXPLICIT_COMPLETE == action.getType());
}
assertTrue("result type", commonResult instanceof DefaultAutocompleteResult);
DefaultAutocompleteResult result = (DefaultAutocompleteResult) commonResult;
assertEquals(expected, result.getAutocompletionText());
}
public void testExplicit() {
checkExplicit(EXPLICIT_BRACES, "");
checkExplicit(EXPLICIT_BRACES, "div.root");
checkExplicit(EXPLICIT_BRACES, "div.root ");
checkExplicit(EXPLICIT_BRACES, "div.root /*foo*/");
checkExplicit(EXPLICIT_BRACES, "div.root /*foo*/ ");
checkExplicit(EXPLICIT_BRACES, ".root ");
checkExplicit(EXPLICIT_BRACES, "@media all");
checkExplicit(EXPLICIT_BRACES, "@media all ");
checkExplicit(EXPLICIT_BRACES, "@media all { td");
checkExplicit(EXPLICIT_BRACES, "@media all /*foo*/");
checkExplicit(EXPLICIT_BRACES, "@media all /*foo*/ ");
checkExplicit(null, "{");
checkExplicit(null, "{ ");
checkExplicit(null, "{ {");
checkExplicit(null, "{ /*");
checkExplicit(null, "{ /* ");
checkExplicit(null, "{ /*foo*/");
checkExplicit(null, "{ /*foo*/ ");
checkExplicit(null, "/*");
checkExplicit(null, "/* ");
checkExplicit(null, ".root /*");
checkExplicit(null, ".root {/*foo*/");
checkExplicit(null, "@media all { td {");
}
public void testOutlineWithMedia() {
JsonStringSet tags = JsonCollections.createStringSet("td");
checkOutlineParser("@media screen { td{}}", tags);
checkOutlineParser("@media screen {td {}}", tags);
}
public void testOutline() {
String text = ""
+ " td,\tp.dark-green, a:hover, [title~=hello]"
// ^^ ^^^^^^^^^^^^ ^^^^^^^ ^^^^^^^^^^^^^^
+ " {\tborder: 3px solid #55AAEE; font: message-box; background-color: #EEEEEE;}"
//
+ " a.bad:visited {background-image:url('gradient2.png');}"
// ^^^^^^^^^^^^^
+ "b/*comment*/.sparse, #para, div#main { -custom:'img {';}"
// ^-----------^^^^^^^ ^^^^^ ^^^^^^^^
+ " .marked p, p > i:first-child {}"
// ^^^^^^^^^ ^^-^-^^^^^^^^^^^^^^
+ " q:lang(no) {quotes: \"~\" \"~\";}\n"
// ^^^^^^^^^^
;
JsonStringSet tags = JsonCollections.createStringSet("td", "p.dark-green", "a:hover",
"[title~=hello]", "a.bad:visited", "b.sparse", "#para", "div#main", ".marked p",
"p > i:first-child", "q:lang(no)");
checkOutlineParser(text, tags);
}
private void checkOutlineParser(String text, JsonStringSet expectedNodes) {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("foo.css"), text, 0, 0, true);
ListenerManager<DocumentParser.Listener> registrar = ListenerManager.create();
final JsonArray<OutlineNode> output = JsonCollections.createArray();
OutlineConsumer consumer = new OutlineConsumer() {
@Override
public void onOutlineParsed(JsonArray<OutlineNode> nodes) {
output.clear();
output.addAll(nodes);
}
};
Line line = helper.editor.getDocument().getFirstLine();
JsonArray<Token> tokens = helper.parser
.parseLineSync(line);
CssOutlineParser cssOutlineParser = new CssOutlineParser(registrar, consumer);
cssOutlineParser.onIterationStart(0);
cssOutlineParser.onDocumentLineParsed(line, 0, tokens);
cssOutlineParser.onIterationFinish();
final int outputSize = output.size();
assertEquals("number of nodes", expectedNodes.getKeys().size(), outputSize);
for (int i = 0; i < outputSize; i++) {
OutlineNode node = output.get(i);
String nodeName = node.getName();
assertTrue("unexpected item: [" + nodeName + "]", expectedNodes.contains(nodeName));
}
cssOutlineParser.cleanup();
}
public void testWorkflow() {
final MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
// TODO: vars in the global scope are not registered by CM.
String text = "td { cur";
helper.setup(new PathUtil("foo.css"), text, 0, text.length(), true);
final MockAutocompleterEnvironment.MockAutocompleter autocompleter = helper.autocompleter;
final JsonArray<Scheduler.ScheduledCommand> scheduled = JsonCollections.createArray();
Runnable ctrlSpaceClicker = new Runnable() {
@Override
public void run() {
autocompleter.pressKey(
new SignalEventEssence(' ', true, false, false, false, KeySignalType.INPUT));
}
};
TestSchedulerImpl.AngryScheduler scheduler = new TestSchedulerImpl.AngryScheduler() {
@Override
public void scheduleDeferred(ScheduledCommand scheduledCommand) {
scheduled.add(scheduledCommand);
}
};
TestSchedulerImpl.runWithSpecificScheduler(ctrlSpaceClicker, scheduler);
assertEquals("actual autocompletion is deferred", 1, scheduled.size());
scheduled.get(0).execute();
assertFalse("expect nonempty popup", helper.popup.proposals.isEmpty());
scheduled.clear();
Runnable enterClicker = new Runnable() {
@Override
public void run() {
helper.popup.delegate.onSelect(helper.popup.proposals.select(0));
}
};
TestSchedulerImpl.runWithSpecificScheduler(enterClicker, scheduler);
assertEquals("apply proposal is deferred", 1, scheduled.size());
// We expect not to explode at this moment.
scheduled.get(0).execute();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/codemirror/LocalFileIndexTest.java | javatests/com/google/collide/client/code/autocomplete/codemirror/LocalFileIndexTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.codemirror;
import static com.google.collide.client.code.autocomplete.TestUtils.CTRL_SHIFT_SPACE;
import static com.google.collide.client.code.autocomplete.TestUtils.createNameSet;
import static com.google.collide.shared.util.JsonCollections.createStringSet;
import com.google.collide.client.code.autocomplete.AutocompleteProposals;
import com.google.collide.client.code.autocomplete.MockAutocompleterEnvironment;
import com.google.collide.client.code.autocomplete.codegraph.ParsingTask;
import com.google.collide.client.code.autocomplete.integration.TaggableLineUtil;
import com.google.collide.client.documentparser.DocumentParser;
import com.google.collide.client.testutil.CodeMirrorTestCase;
import com.google.collide.client.util.IncrementalScheduler;
import com.google.collide.client.util.PathUtil;
import com.google.collide.codemirror2.Token;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.TaggableLine;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.document.LineFinder;
import com.google.collide.shared.document.LineInfo;
import com.google.collide.shared.document.util.LineUtils;
import com.google.collide.shared.util.JsonCollections;
import com.google.collide.shared.util.ListenerRegistrar.Remover;
import javax.annotation.Nonnull;
/**
* Test cases that check that local file index is built and updates correctly.
*
*/
public class LocalFileIndexTest extends CodeMirrorTestCase {
private ParsingTask analyzer;
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
public void testParse() {
String text = "var aaa;\nvar bbb;\n";
MockAutocompleterEnvironment helper = configureHelper(text);
AutocompleteProposals proposals =
helper.autocompleter.jsAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SHIFT_SPACE);
assertEquals("variable set", createStringSet("aaa", "bbb"), createNameSet(proposals));
}
private MockAutocompleterEnvironment configureHelper(String text) {
final MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("foo.js"), text, 0, 0, true);
analyzer = new ParsingTask(helper.autocompleter.localPrefixIndexStorage);
JsonArray<IncrementalScheduler.Task> parseRequests = helper.parseScheduler.requests;
assertEquals("parsing not scheduled initially", 0, parseRequests.size());
helper.parser.getListenerRegistrar().add(new DocumentParser.Listener() {
private boolean asyncParsing;
@Override
public void onIterationStart(int lineNumber) {
asyncParsing = true;
analyzer.onBeforeParse();
}
@Override
public void onIterationFinish() {
asyncParsing = false;
analyzer.onAfterParse();
}
@Override
public void onDocumentLineParsed(
Line line, int lineNumber, @Nonnull JsonArray<Token> tokens) {
if (asyncParsing) {
TaggableLine previousLine = TaggableLineUtil.getPreviousLine(line);
analyzer.onParseLine(previousLine, line, tokens);
}
}
});
helper.parser.begin();
assertEquals("parse scheduled", 1, parseRequests.size());
parseRequests.get(0).run(50);
parseRequests.clear();
return helper;
}
public void testDeleteLines() {
String text = ""
+ "var aaa;\n"
+ "var bbb;\n"
+ "var ccc;\n"
+ "var ddd;\n"
+ "var eee;\n"
+ "var fff;\n";
MockAutocompleterEnvironment helper = configureHelper(text);
AutocompleteProposals proposals =
helper.autocompleter.jsAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SHIFT_SPACE);
assertEquals("variable set", createStringSet(
"aaa", "bbb", "ccc", "ddd", "eee", "fff"), createNameSet(proposals));
Document document = helper.editor.getDocument();
Remover remover = document.getLineListenerRegistrar().add(new Document.LineListener() {
@Override
public void onLineAdded(Document document, int lineNumber, JsonArray<Line> addedLines) {
}
@Override
public void onLineRemoved(Document document, int lineNumber,
JsonArray<Line> removedLines) {
JsonArray<TaggableLine> deletedLines = JsonCollections.createArray();
for (final Line line : removedLines.asIterable()) {
deletedLines.add(line);
}
analyzer.onLinesDeleted(deletedLines);
}
});
LineFinder lineFinder = document.getLineFinder();
LineInfo line2 = lineFinder.findLine(2);
LineInfo line4 = lineFinder.findLine(4);
String textToDelete = LineUtils.getText(line2.line(), 0, line4.line(), 0);
helper.editor.getEditorDocumentMutator().deleteText(line2.line(), 2, 0, textToDelete.length());
remover.remove();
JsonArray<IncrementalScheduler.Task> parseRequests = helper.parseScheduler.requests;
assertEquals("reparse scheduled", 1, parseRequests.size());
parseRequests.get(0).run(50);
proposals = helper.autocompleter.jsAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SHIFT_SPACE);
assertEquals("new variable set", createStringSet(
"aaa", "bbb", "eee", "fff"), createNameSet(proposals));
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/codemirror/PyCodemirrorTest.java | javatests/com/google/collide/client/code/autocomplete/codemirror/PyCodemirrorTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.codemirror;
import static com.google.collide.client.code.autocomplete.TestUtils.CTRL_SPACE;
import com.google.collide.client.code.autocomplete.AutocompleteProposals;
import com.google.collide.client.code.autocomplete.MockAutocompleterEnvironment;
import com.google.collide.client.code.autocomplete.codegraph.CompletionContext;
import com.google.collide.client.code.autocomplete.codegraph.py.PyProposalBuilder;
import com.google.collide.client.testutil.CodeMirrorTestCase;
import com.google.collide.client.util.PathUtil;
import com.google.collide.codemirror2.PyState;
import com.google.collide.codemirror2.Token;
import com.google.collide.codemirror2.TokenType;
import com.google.collide.json.shared.JsonArray;
/**
* Test for PY autocompletion cases, when codemirror parser is used.
*
*/
public class PyCodemirrorTest extends CodeMirrorTestCase {
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
public void testNoProposalsInCommentsAndStrings() {
// 0 1 2
// 01234567890123456789012345
String text = "a = 'Hello Kitty' # Funny?";
checkHasProposals(text, 0, true, "global");
checkHasProposals(text, 4, true, "before string");
checkHasProposals(text, 5, false, "string began");
checkHasProposals(text, 11, false, "in string after space");
checkHasProposals(text, 15, false, "in string");
checkHasProposals(text, 17, true, "after string");
checkHasProposals(text, 18, true, "before comment");
checkHasProposals(text, 20, false, "in comment after space");
checkHasProposals(text, 23, false, "in comment");
}
private void checkHasProposals(String text, int column,
boolean expectHasProposals, String message) {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("foo.py"), text, 0, column, true);
AutocompleteProposals proposals = helper.autocompleter.pyAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
assertEquals(message, expectHasProposals, proposals.size() > 0);
}
public void testContextBuilding() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
String text = "a .bc.de .f";
helper.setup(new PathUtil("foo.py"), text, 0, text.length(), true);
PyProposalBuilder proposalBuilder = new PyProposalBuilder();
CompletionContext<PyState> completionContext = proposalBuilder
.buildContext(helper.editor.getSelection(), helper.parser);
assertEquals("previous context", "a.bc.de.", completionContext.getPreviousContext());
assertEquals("triggering string", "f", completionContext.getTriggeringString());
}
public void testTemplateProposalsInGlobal() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("foo.py"), "con", 0, 3, true);
AutocompleteProposals autocompletions =
helper.autocompleter.pyAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
AutocompleteProposals.ProposalWithContext proposal = autocompletions.select(0);
assertEquals("proposal name", "continue", proposal.getItem().getName());
helper.autocompleter.reallyFinishAutocompletion(proposal);
String text = helper.editor.getDocument().getFirstLine().getText();
assertEquals("resulting text", "continue\n", text);
}
public void testOperatorKeywords() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
String text = "if a is not None:";
helper.setup(new PathUtil("foo.py"), text, 0, text.length(), true);
JsonArray<Token> tokens = helper.parser
.parseLineSync(helper.editor.getDocument().getFirstLine());
assertEquals("4-th token == 'is'", "is", tokens.get(4).getValue());
assertEquals("4-th token is keyword", TokenType.KEYWORD, tokens.get(4).getType());
assertEquals("6-th token == 'not'", "not", tokens.get(6).getValue());
assertEquals("6-th token is keyword", TokenType.KEYWORD, tokens.get(6).getType());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/codemirror/HtmlCodemirrorTest.java | javatests/com/google/collide/client/code/autocomplete/codemirror/HtmlCodemirrorTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.codemirror;
import static com.google.collide.client.code.autocomplete.TestUtils.CTRL_SHIFT_SPACE;
import static com.google.collide.client.code.autocomplete.TestUtils.CTRL_SPACE;
import static com.google.collide.client.codeunderstanding.CodeGraphTestUtils.createCodeGraph;
import static com.google.collide.client.codeunderstanding.CodeGraphTestUtils.createFreshness;
import static org.waveprotocol.wave.client.common.util.SignalEvent.KeySignalType;
import com.google.collide.client.code.autocomplete.AutocompleteProposals;
import com.google.collide.client.code.autocomplete.AutocompleteResult;
import com.google.collide.client.code.autocomplete.DefaultAutocompleteResult;
import com.google.collide.client.code.autocomplete.LanguageSpecificAutocompleter.ExplicitAction;
import com.google.collide.client.code.autocomplete.LanguageSpecificAutocompleter.ExplicitActionType;
import com.google.collide.client.code.autocomplete.MockAutocompleterEnvironment;
import com.google.collide.client.code.autocomplete.SignalEventEssence;
import com.google.collide.client.code.autocomplete.TestUtils;
import com.google.collide.client.code.autocomplete.codegraph.ParsingTask;
import com.google.collide.client.code.autocomplete.integration.DocumentParserListenerAdapter;
import com.google.collide.client.code.autocomplete.integration.TaggableLineUtil;
import com.google.collide.client.testutil.CodeMirrorTestCase;
import com.google.collide.client.util.PathUtil;
import com.google.collide.codemirror2.Token;
import com.google.collide.dto.CodeBlock;
import com.google.collide.dto.client.DtoClientImpls;
import com.google.collide.dto.client.DtoClientImpls.CodeBlockImpl;
import com.google.collide.dto.client.DtoClientImpls.CodeGraphImpl;
import com.google.collide.dto.client.DtoClientImpls.CodeGraphResponseImpl;
import com.google.collide.dto.client.DtoClientImpls.MockCodeBlockImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.TaggableLine;
import com.google.collide.shared.document.Line;
/**
* Test for various auto-completion cases, when CodeMirror parser is used.
*/
public class HtmlCodemirrorTest extends CodeMirrorTestCase {
private static void setupHelper(MockAutocompleterEnvironment helper, String text) {
helper.setup(new PathUtil("foo.html"), text, 0, text.length(), true);
helper.parser.begin();
}
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
public void testExplicit() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
setupHelper(helper, "<html><body><");
AutocompleteResult commonResult = helper.autocompleter.htmlAutocompleter
.getExplicitAction(helper.editor.getSelection(), new SignalEventEssence('/'), false)
.getExplicitAutocompletion();
assertTrue("result type", commonResult instanceof DefaultAutocompleteResult);
DefaultAutocompleteResult result = (DefaultAutocompleteResult) commonResult;
assertEquals("/body>", result.getAutocompletionText());
}
public void testCssFindAutocompletions() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
setupHelper(helper, "<html><head><style>p {color:bl");
Line line = helper.editor.getDocument().getLastLine();
JsonArray<Token> tokens = helper.parser.parseLineSync(line);
assertEquals("html", tokens.get(0).getMode());
assertEquals("css", tokens.get(tokens.size() - 1).getMode());
AutocompleteProposals proposals =
helper.autocompleter.htmlAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
assertEquals(2, proposals.size());
assertEquals("blue", proposals.get(1).getName());
}
public void testCssFindAutocompletionsAfterEmptyLine() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
String line0 = "<html><head><style>p {color:";
String line1 = "";
String line2 = "bl";
String text = line0 + "\n" + line1 + "\n" + line2;
helper.setup(new PathUtil("foo.html"), text, 2, line2.length(), true);
helper.parser.begin();
Line line = helper.editor.getDocument().getFirstLine();
JsonArray<Token> tokens = helper.parser.parseLineSync(line);
assertEquals("html", tokens.get(0).getMode());
assertEquals("css", tokens.get(tokens.size() - 2).getMode());
assertEquals("", tokens.get(tokens.size() - 1).getMode());
line = helper.editor.getDocument().getLineFinder().findLine(1).line();
tokens = helper.parser.parseLineSync(line);
assertEquals(1, tokens.size());
assertEquals("", tokens.get(0).getMode());
line = helper.editor.getDocument().getLastLine();
tokens = helper.parser.parseLineSync(line);
assertEquals(1, tokens.size());
assertEquals("css", tokens.get(0).getMode());
AutocompleteProposals proposals =
helper.autocompleter.htmlAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
assertEquals(2, proposals.size());
assertEquals("blue", proposals.get(1).getName());
}
public void testCssGetExplicitAutocompletion() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
setupHelper(helper, "<html><head><style>p ");
Line line = helper.editor.getDocument().getLastLine();
JsonArray<Token> tokens = helper.parser.parseLineSync(line);
assertEquals("html", tokens.get(0).getMode());
assertEquals("css", tokens.get(tokens.size() - 1).getMode());
helper.autocompleter.htmlAutocompleter.updateModeAnchors(line, tokens);
SignalEventEssence trigger = new SignalEventEssence('{');
AutocompleteResult result = helper.autocompleter.htmlAutocompleter
.getExplicitAction(helper.editor.getSelection(), trigger, false)
.getExplicitAutocompletion();
assertTrue("result type", result instanceof DefaultAutocompleteResult);
DefaultAutocompleteResult defaultResult = (DefaultAutocompleteResult) result;
assertEquals("{\n \n}", defaultResult.getAutocompletionText());
}
public void testAfterCssMultiplexing() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
setupHelper(helper, "<html><head><style>p {color:blue;}</style><a");
AutocompleteProposals proposals =
helper.autocompleter.htmlAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
assertEquals(7, proposals.size());
assertEquals("abbr", proposals.get(1).getName());
}
public void testJavascriptFindAutocompletions() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
setupHelper(helper,
"<html><body><script type=\"text/javascript\">function a() { var abba, apple, arrow; a");
Line line = helper.editor.getDocument().getLastLine();
JsonArray<Token> tokens = helper.parser.parseLineSync(line);
assertEquals("html", tokens.get(0).getMode());
assertEquals("javascript", tokens.get(tokens.size() - 1).getMode());
TaggableLine previousLine = TaggableLineUtil.getPreviousLine(line);
helper.autocompleter.htmlAutocompleter.updateModeAnchors(line, tokens);
new ParsingTask(helper.autocompleter.localPrefixIndexStorage).onParseLine(
previousLine, line, tokens);
AutocompleteProposals proposals = helper.autocompleter.htmlAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SHIFT_SPACE);
assertEquals(3, proposals.size());
assertEquals("apple", proposals.get(1).getName());
proposals = helper.autocompleter.htmlAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
assertEquals(4, proposals.size());
assertEquals("arguments", proposals.get(2).getName());
}
public void testJavascriptFindAutocompletionsOnEmptyLine() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("foo.html"),
"<html><head><script>\n\n</script></head></html>", 1, 0, true);
helper.parser.getListenerRegistrar().add(new DocumentParserListenerAdapter(
helper.autocompleter, helper.editor));
helper.parser.begin();
helper.parseScheduler.requests.pop().run(10);
AutocompleteProposals proposals = helper.autocompleter.htmlAutocompleter
.findAutocompletions(helper.editor.getSelection(), CTRL_SPACE);
assertTrue(TestUtils.findProposalByName(proposals.getItems(), "break") != null);
}
public void testJavascriptApplyAutocompletions() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
String prologue = "<html>\n<script type=\"text/javascript\">\n";
String epilogue = "</script>\n</html>\n";
String text = prologue + "d\n" + epilogue;
helper.setup(new PathUtil("foo.html"), text, 2, 1, true);
helper.parser.begin();
helper.parseScheduler.requests.get(0).run(10);
AutocompleteProposals proposals = helper.autocompleter.htmlAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
assertEquals(3, proposals.size());
assertEquals("delete", proposals.get(1).getName());
helper.autocompleter.reallyFinishAutocompletion(proposals.select(1));
assertEquals(prologue + "delete \n" + epilogue, helper.editor.getDocument().asText());
}
public void testJavascriptFindAutocompletionsSeesFunctionInCodegraph() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
// Something like function aFoo() {}
CodeBlockImpl aFoo = MockCodeBlockImpl
.make()
.setBlockType(CodeBlock.Type.VALUE_FUNCTION)
.setName("aFoo")
.setChildren(JsoArray.<CodeBlock>create())
.setStartLineNumber(0)
.setStartColumn(0)
.setEndLineNumber(0)
.setEndColumn(19);
CodeBlockImpl fileCodeBlock = MockCodeBlockImpl
.make()
.setBlockType(CodeBlock.Type.VALUE_FILE)
.setName("/foo.js")
.setChildren(JsoArray.<CodeBlock>from(aFoo))
.setStartLineNumber(0)
.setStartColumn(0)
.setEndLineNumber(0)
.setEndColumn(19);
CodeGraphImpl codeGraph = createCodeGraph(fileCodeBlock);
CodeGraphResponseImpl response = DtoClientImpls.MockCodeGraphResponseImpl.make();
response.setFreshness(createFreshness("0", "1", "0"));
response.setFullGraphJson(codeGraph.serialize());
// This will immediately fire api call
helper.cubeClient.setPath("/foo.js");
assertEquals("one api call after setDocument", 1,
helper.cubeClient.api.collectedCallbacks.size());
helper.cubeClient.api.collectedCallbacks.get(0).onMessageReceived(response);
setupHelper(helper,
"<html><body><script type=\"text/javascript\">function a() { var abba, apple, arrow; a");
Line line = helper.editor.getDocument().getLastLine();
JsonArray<Token> tokens = helper.parser.parseLineSync(line);
assertEquals("html", tokens.get(0).getMode());
assertEquals("javascript", tokens.get(tokens.size() - 1).getMode());
TaggableLine previousLine = TaggableLineUtil.getPreviousLine(line);
helper.autocompleter.htmlAutocompleter.updateModeAnchors(line, tokens);
new ParsingTask(helper.autocompleter.localPrefixIndexStorage).onParseLine(
previousLine, line, tokens);
AutocompleteProposals proposals = helper.autocompleter.htmlAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SHIFT_SPACE);
assertEquals(3, proposals.size());
assertEquals("apple", proposals.get(1).getName());
proposals = helper.autocompleter.htmlAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
assertEquals(5, proposals.size());
assertEquals("aFoo", proposals.get(1).getName());
}
public void testJavascriptGetExplicitAutocompletion() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
setupHelper(helper, "<html><body><script type=\"text/javascript\">foo");
Line line = helper.editor.getDocument().getLastLine();
JsonArray<Token> tokens = helper.parser.parseLineSync(line);
assertEquals("html", tokens.get(0).getMode());
assertEquals("javascript", tokens.get(tokens.size() - 1).getMode());
TaggableLine previousLine = TaggableLineUtil.getPreviousLine(line);
helper.autocompleter.htmlAutocompleter.updateModeAnchors(line, tokens);
new ParsingTask(helper.autocompleter.localPrefixIndexStorage).onParseLine(
previousLine, line, tokens);
SignalEventEssence trigger = new SignalEventEssence('[');
AutocompleteResult result = helper.autocompleter.htmlAutocompleter
.getExplicitAction(helper.editor.getSelection(), trigger, false)
.getExplicitAutocompletion();
assertTrue("result type", result instanceof DefaultAutocompleteResult);
DefaultAutocompleteResult defaultResult = (DefaultAutocompleteResult) result;
assertEquals("[]", defaultResult.getAutocompletionText());
trigger = new SignalEventEssence('(');
result = helper.autocompleter.htmlAutocompleter
.getExplicitAction(helper.editor.getSelection(), trigger, false)
.getExplicitAutocompletion();
assertTrue("result type", result instanceof DefaultAutocompleteResult);
defaultResult = (DefaultAutocompleteResult) result;
assertEquals("()", defaultResult.getAutocompletionText());
}
public void testPopupDoNotAnnoyUsers() {
final MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("foo.html"),
"<html>\n <body>\n <script>\n\n </script>\n </body>\n</html>", 3, 0, true);
ExplicitActionType action = helper.autocompleter.htmlAutocompleter.getExplicitAction(
helper.editor.getSelection(), new SignalEventEssence(' '), false).getType();
assertTrue("no popup before mode is determined", action == ExplicitActionType.DEFAULT);
helper.parser.getListenerRegistrar().add(new DocumentParserListenerAdapter(
helper.autocompleter, helper.editor));
helper.parser.begin();
helper.parseScheduler.requests.pop().run(10);
action = helper.autocompleter.htmlAutocompleter.getExplicitAction(
helper.editor.getSelection(), new SignalEventEssence(' '), false).getType();
assertTrue("no popup in JS mode", action == ExplicitActionType.DEFAULT);
}
public void testNoPopupAfterClosingTag() {
final MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("foo.html"), "<html>\n <script\n<body style=''>\n", 2, 8, true);
helper.parser.getListenerRegistrar().add(new DocumentParserListenerAdapter(
helper.autocompleter, helper.editor));
helper.parser.begin();
helper.parseScheduler.requests.pop().run(10);
SignalEventEssence signalGt = new SignalEventEssence(
'>', false, false, true, false, KeySignalType.INPUT);
ExplicitActionType action = helper.autocompleter.htmlAutocompleter.getExplicitAction(
helper.editor.getSelection(), signalGt, false).getType();
assertTrue("no popup after closing tag", action == ExplicitActionType.DEFAULT);
}
/**
* Tests a sharp edge: when html parser changes it's mode.
*
* <p>Parser changes it's mode when it meets ">" that finishes opening
* "script" tag.
*
* <p>As a consequence, xml-analyzer may interpret the following
* content "inside-out".
*/
public void testScriptTagDoNotConfuseXmlProcessing() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("foo.html"),
"<html>\n <script></script>\n <body>\n", 2, 7, true);
helper.parser.getListenerRegistrar().add(new DocumentParserListenerAdapter(
helper.autocompleter, helper.editor));
helper.parser.begin();
helper.parseScheduler.requests.pop().run(10);
AutocompleteProposals proposals = helper.autocompleter.htmlAutocompleter
.findAutocompletions(helper.editor.getSelection(), CTRL_SPACE);
assertEquals(0, proposals.size());
}
/**
* Tests a sharp edge: when html parser changes it's mode.
*
* <p>Parser changes it's mode when it meets ">" that finishes opening
* "script" tag.
*
* <p>This situation could confuse autocompleter and cause unwanted popup
* when user press space just after ">".
*/
public void testNoJsPopupOnAfterSpace() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("foo.html"),
"<html>\n <script>\n", 1, 9, true);
helper.parser.getListenerRegistrar().add(new DocumentParserListenerAdapter(
helper.autocompleter, helper.editor));
helper.parser.begin();
helper.parseScheduler.requests.pop().run(10);
ExplicitAction action = helper.autocompleter.htmlAutocompleter
.getExplicitAction(helper.editor.getSelection(), new SignalEventEssence(' '), false);
assertFalse(action.getType() == ExplicitActionType.DEFERRED_COMPLETE);
}
/**
* Tests a sharp edge: when html parser is asked for proposals on line that
* is not parsed yet.
*
* <p>Previously we got NPE in this case.
*/
public void testNoProposalsOnGrayLine() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("foo.html"),
"<html>\n <body>\n <di", 2, 5, true);
helper.parser.getListenerRegistrar().add(new DocumentParserListenerAdapter(
helper.autocompleter, helper.editor));
helper.parser.begin();
helper.parseScheduler.requests.pop().run(1);
AutocompleteProposals proposals = helper.autocompleter.htmlAutocompleter
.findAutocompletions(helper.editor.getSelection(), CTRL_SPACE);
assertEquals(0, proposals.size());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/codemirror/JsCodemirrorTest.java | javatests/com/google/collide/client/code/autocomplete/codemirror/JsCodemirrorTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.codemirror;
import static com.google.collide.client.code.autocomplete.TestUtils.CTRL_SPACE;
import static com.google.gwt.event.dom.client.KeyCodes.KEY_BACKSPACE;
import static org.waveprotocol.wave.client.common.util.SignalEvent.KeySignalType.DELETE;
import com.google.collide.client.code.autocomplete.AutocompleteProposals;
import com.google.collide.client.code.autocomplete.AutocompleteProposals.ProposalWithContext;
import com.google.collide.client.code.autocomplete.AutocompleteResult;
import com.google.collide.client.code.autocomplete.DefaultAutocompleteResult;
import com.google.collide.client.code.autocomplete.LanguageSpecificAutocompleter;
import com.google.collide.client.code.autocomplete.LanguageSpecificAutocompleter.ExplicitAction;
import com.google.collide.client.code.autocomplete.LanguageSpecificAutocompleter.ExplicitActionType;
import com.google.collide.client.code.autocomplete.MockAutocompleterEnvironment;
import com.google.collide.client.code.autocomplete.MockAutocompleterEnvironment.MockAutocompleter;
import com.google.collide.client.code.autocomplete.SignalEventEssence;
import com.google.collide.client.code.autocomplete.TestUtils;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.editor.input.TestSignalEvent;
import com.google.collide.client.testutil.CodeMirrorTestCase;
import com.google.collide.client.testutil.TestSchedulerImpl;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.util.input.ModifierKeys;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringSet;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.util.LineUtils;
import com.google.collide.shared.util.JsonCollections;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.KeyCodes;
import org.waveprotocol.wave.client.common.util.SignalEvent.KeySignalType;
import javax.annotation.Nullable;
/**
* Test for JS autocompletion cases, when CodeMirror parser is used.
*
*/
public class JsCodemirrorTest extends CodeMirrorTestCase {
static final SignalEventEssence DELETE_KEY = new SignalEventEssence(
KEY_BACKSPACE, false, false, false, false, DELETE);
private static final SignalEventEssence ENTER = new SignalEventEssence(
KeyCodes.KEY_ENTER, false, false, false, false, KeySignalType.INPUT);
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
public void testNoProposalsInCommentsAndStrings() {
// 0 1 2
// 012345678901234567890123456789
String text1 = "var a = 'Hello Kitty'; // Funny?";
String text2 = "var b = /* Aha =) */ 0;";
checkHasProposals(text1, 0, true, "global");
checkHasProposals(text1, 8, true, "before string");
checkHasProposals(text1, 9, false, "string began");
checkHasProposals(text1, 10, false, "in string");
checkHasProposals(text1, 15, false, "in string after space");
checkHasProposals(text1, 21, true, "after string");
checkHasProposals(text1, 22, true, "after string");
checkHasProposals(text1, 23, true, "before comment");
checkHasProposals(text1, 26, false, "in comment after space");
checkHasProposals(text1, 30, false, "in comment");
checkHasProposals(text2, 0, true, "after comment");
checkHasProposals(text2, 8, true, "before multiline");
checkHasProposals(text2, 13, false, "in multiline");
checkHasProposals(text2, 15, false, "in multiline after space");
checkHasProposals(text2, 21, true, "after multiline");
}
private void checkHasProposals(String text, int column,
boolean expectHasProposals, String message) {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("foo.js"), text, 0, column, true);
AutocompleteProposals proposals = helper.autocompleter.jsAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
assertEquals(message, expectHasProposals, !proposals.isEmpty());
}
public void testNoTemplateProposalsAfterThis() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("foo.js"), "this.", 0, 5, true);
AutocompleteProposals proposals = helper.autocompleter.jsAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
assertTrue("has no proposals", proposals.isEmpty());
}
public void testTemplateProposalsInGlobal() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("foo.js"), "", 0, 0, true);
AutocompleteProposals autocompletions =
helper.autocompleter.jsAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
assertFalse("has proposals", autocompletions.isEmpty());
ProposalWithContext whileProposal = TestUtils.selectProposalByName(autocompletions, "while");
assertNotNull("has 'while'", whileProposal);
helper.autocompleter.reallyFinishAutocompletion(whileProposal);
assertEquals("while () {\n \n}", helper.editor.getDocument().asText());
}
public void testAutocompletionAfterKeyword() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("foo.js"), "for", 0, 3, true);
AutocompleteProposals autocompletions =
helper.autocompleter.jsAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
ProposalWithContext proposal = autocompletions.select(0);
assertEquals("proposal name", "for", proposal.getItem().getName());
helper.autocompleter.reallyFinishAutocompletion(proposal);
String text = helper.editor.getDocument().getFirstLine().getText();
assertEquals("resulting text", "for (;;) {\n", text);
}
public void testDoNotDieOnLongLines() {
String longLine = " ";
for (int i = 0; i < 12; i++) {
longLine = longLine + longLine;
}
// longLine length is 4096
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
String text = "function foo() {\n"
+ " var bar1;\n"
+ " var bar2 ='" + longLine + "';\n"
+ " var bar3;\n"
+ " " // Cursor here.
+ "}";
helper.setup(new PathUtil("foo.js"), text, 4, 2, true);
helper.parser.begin();
helper.parseScheduler.requests.get(0).run(10);
AutocompleteProposals autocompletions =
helper.autocompleter.jsAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
JsonStringSet proposals = JsonCollections.createStringSet();
for (int i = 0, l = autocompletions.size(); i < l; i++) {
proposals.add(autocompletions.get(i).getName());
}
assertTrue("contains var defined before long line", proposals.contains("bar1"));
assertTrue("contains var defined after long line", proposals.contains("bar3"));
}
public void testDoNotDieOnRegExp() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
String text = "function foo() {\n"
+ " var bar1 = /regexp/;\n"
+ " var bar2;\n"
+ " " // Cursor here.
+ "}";
helper.setup(new PathUtil("foo.js"), text, 3, 2, true);
helper.parser.begin();
helper.parseScheduler.requests.get(0).run(10);
AutocompleteProposals autocompletions =
helper.autocompleter.jsAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
JsonStringSet proposals = JsonCollections.createStringSet();
for (int i = 0, l = autocompletions.size(); i < l; i++) {
proposals.add(autocompletions.get(i).getName());
}
assertTrue("contains var defined in line with regexp", proposals.contains("bar1"));
assertTrue("contains var defined after line with regexp", proposals.contains("bar2"));
}
public void testDeleteAtBeginningOfDocument() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
String text = "<cursorAtTheBeginingOfFirstLine>";
helper.setup(new PathUtil("foo.js"), text, 0, 0, true);
ExplicitAction action = helper.autocompleter.jsAutocompleter.getExplicitAction(
helper.editor.getSelection(), DELETE_KEY, false);
assertEquals(LanguageSpecificAutocompleter.ExplicitActionType.DEFAULT, action.getType());
}
public void testClosePopupOnSpace() {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
// TODO: vars in the global scope are not registered by CM.
String text = "function a() { var abba, apple, arrow; a";
helper.setup(new PathUtil("foo.js"), text, 0, text.length(), true);
final MockAutocompleter autocompleter = helper.autocompleter;
assertFalse("initially popup is not shown", helper.popup.isShowing());
final JsonArray<Scheduler.ScheduledCommand> scheduled = JsonCollections.createArray();
// We want to click ctrl-space.
Runnable ctrlSpaceClicker = new Runnable() {
@Override
public void run() {
autocompleter.pressKey(CTRL_SPACE);
}
};
// Collect deferred tasks in array.
TestSchedulerImpl.AngryScheduler scheduler = new TestSchedulerImpl.AngryScheduler() {
@Override
public void scheduleDeferred(ScheduledCommand scheduledCommand) {
scheduled.add(scheduledCommand);
}
};
// Now, if we hit ctrl-space - popup will appear with 3 variables.
TestSchedulerImpl.runWithSpecificScheduler(ctrlSpaceClicker, scheduler);
assertEquals("actual autocompletion is deferred", 1, scheduled.size());
// Now autocompletion acts.
scheduled.get(0).execute();
assertTrue("popup appeared", helper.popup.isShowing());
assertEquals("variables are proposed", 4, helper.popup.proposals.size());
// Now, if we type " " autocompletion popup should disappear.
autocompleter.pressKey(new SignalEventEssence(' '));
assertFalse("popup disappeared", helper.popup.isShowing());
}
public void testRawExplicitInContext() {
SignalEventEssence quoteKey = new SignalEventEssence('"');
checkExplicit("line-comment", "// var a =", 0, quoteKey, null);
checkExplicit("in-block-comment", "/* var a = */", 3, quoteKey, null);
checkExplicit("block-comment-eol", "/* var a =\nsecond line*/", 0, quoteKey, null);
checkExplicit("in-string", "var a =''", 1, quoteKey, null);
checkExplicit("bs-in-string", "var a ='\"\"'", 2, DELETE_KEY, null);
checkExplicit("bs-in-comment", "// var a =''", 1, DELETE_KEY, null);
checkExplicit("bs-between-string", "var a ='''", 1, DELETE_KEY, null);
}
public void testBracesPairing() {
checkExplicit("braces-pairing", "foo", 0, new SignalEventEssence('['),
new DefaultAutocompleteResult("[]", "", 1));
}
public void testBracesNotPairing() {
checkExplicit("braces-not-pairing", "foo", 3, new SignalEventEssence('['), null);
}
public void testQuotesPairing() {
checkExplicit("quotes-pairing", "", 0, new SignalEventEssence('"'),
new DefaultAutocompleteResult("\"\"", "", 1));
}
public void testQuotesNotPairing() {
checkExplicit("quotes-not-pairing", "\"\"", 0, new SignalEventEssence('"'), null);
}
public void testBracesPassing() {
checkExplicit(
"braces-passing", "foo[]", 1, new SignalEventEssence(']'),
DefaultAutocompleteResult.PASS_CHAR);
}
public void testBracesNotPassing() {
checkExplicit("braces-not-passing", "[(()]", 2, new SignalEventEssence(')'), null);
}
public void testSymmetricDeletion() {
DefaultAutocompleteResult bsDelete = new DefaultAutocompleteResult(
"", 0, 1, 0, 1, null, "");
checkExplicit("bs-after-comment", "/* Q */ var a =''", 1, DELETE_KEY, bsDelete);
checkExplicit("bs-braces", "foo[]", 1, DELETE_KEY, bsDelete);
}
public void testEnterBetweenCurlyBraces() {
checkExplicit("enter-between-curly-braces", " {}", 1, ENTER,
new DefaultAutocompleteResult("\n \n ", "", 5));
}
private void checkExplicit(String message, String text, int tailOffset,
SignalEventEssence trigger, @Nullable DefaultAutocompleteResult expected) {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
Document document = Document.createFromString(text);
int column = LineUtils.getLastCursorColumn(document.getFirstLine()) - tailOffset;
helper.setup(new PathUtil("foo.js"), document, 0, column, true);
ExplicitAction action = helper.autocompleter.jsAutocompleter.getExplicitAction(
helper.editor.getSelection(), trigger, false);
AutocompleteResult commonResult = action.getExplicitAutocompletion();
if (expected == null) {
assertNull("result", commonResult);
assertFalse("action", ExplicitActionType.EXPLICIT_COMPLETE == action.getType());
return;
} else {
assertTrue("action", ExplicitActionType.EXPLICIT_COMPLETE == action.getType());
}
assertTrue("result type", commonResult instanceof DefaultAutocompleteResult);
DefaultAutocompleteResult result = (DefaultAutocompleteResult) commonResult;
assertNotNull(message + ":result", result);
assertEquals(message + ":text",
expected.getAutocompletionText(), result.getAutocompletionText());
assertEquals(message + ":delete", expected.getDeleteCount(), result.getDeleteCount());
assertEquals(message + ":bspace", expected.getBackspaceCount(), result.getBackspaceCount());
assertEquals(message + ":jump", expected.getJumpLength(), result.getJumpLength());
}
/**
* Integration test: check that
* {@link com.google.collide.client.code.autocomplete.codegraph.CodeGraphAutocompleter}
* allows
* {@link com.google.collide.client.editor.input.DefaultScheme} to
* perform specific textual changes.
*/
public void testDoNotPreventCtrlBs() {
String text = "#!@abc ";
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("test.js"), text, 0, text.length(), true);
final Editor editor = helper.editor;
final JsonArray<Scheduler.ScheduledCommand> scheduled = JsonCollections.createArray();
TestSchedulerImpl.AngryScheduler scheduler = new TestSchedulerImpl.AngryScheduler() {
@Override
public void scheduleDeferred(ScheduledCommand scheduledCommand) {
scheduled.add(scheduledCommand);
}
};
Runnable ctrlBsClicker = new Runnable() {
@Override
public void run() {
TestSignalEvent bsTrigger = new TestSignalEvent(
KeyCodes.KEY_BACKSPACE, KeySignalType.DELETE, ModifierKeys.ACTION);
editor.getInput().processSignalEvent(bsTrigger);
}
};
TestSchedulerImpl.runWithSpecificScheduler(ctrlBsClicker, scheduler);
while (!scheduled.isEmpty()) {
Scheduler.ScheduledCommand command = scheduled.remove(0);
command.execute();
}
String result2 = editor.getDocument().getFirstLine().getText();
assertEquals("after ctrl-BS", "#!@", result2);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/codegraph/ScopeTrieBuilderTest.java | javatests/com/google/collide/client/code/autocomplete/codegraph/ScopeTrieBuilderTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.codegraph;
import com.google.collide.client.code.autocomplete.AutocompleteProposal;
import com.google.collide.client.code.autocomplete.Autocompleter;
import com.google.collide.client.code.autocomplete.TestUtils;
import com.google.collide.client.code.autocomplete.codegraph.CodeGraphAutocompleterTest.MockProposalBuilder;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.collide.client.util.PathUtil;
import com.google.collide.codemirror2.State;
import com.google.collide.codemirror2.SyntaxType;
import com.google.collide.dto.CodeBlock;
import com.google.collide.dto.client.DtoClientImpls.CodeBlockImpl;
import com.google.collide.dto.client.DtoClientImpls.CodeGraphImpl;
import com.google.collide.dto.client.DtoClientImpls.MockCodeBlockImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.json.client.JsoStringSet;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringSet;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.Position;
import com.google.collide.shared.util.JsonCollections;
/**
* Tests for ProposalBuilder.
*
*/
public class ScopeTrieBuilderTest extends SynchronousTestCase {
static final int LAST_COLUMN = 99;
static final String OBJECT_1 = "MyObject";
static final String METHOD_1 = "method1";
static final String METHOD_2 = "method2";
private PathUtil path;
@Override
public void gwtSetUp() throws Exception {
super.gwtSetUp();
path = new PathUtil("/foo.js");
}
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
private CodeBlockImpl createCodeBlockTree() {
// We create code blocks for the following pseudo-code:
// MyObject {
// function method1() {
// }
// function method2() {
// var var1 {
// foo: ''
// }
// }
// }
CodeBlockImpl contextFile = MockCodeBlockImpl
.make()
.setId("0")
.setName(path.getPathString())
.setBlockType(CodeBlock.Type.VALUE_FILE)
.setStartLineNumber(0)
.setStartColumn(0)
.setEndLineNumber(0)
.setEndColumn(LAST_COLUMN)
.setChildren(JsoArray.<CodeBlock>create());
CodeBlockImpl objectBlock = MockCodeBlockImpl
.make()
.setId("1")
.setBlockType(CodeBlock.Type.VALUE_FIELD)
.setName(OBJECT_1)
.setStartLineNumber(0)
.setStartColumn(0)
.setEndLineNumber(0)
.setEndColumn(LAST_COLUMN)
.setChildren(JsoArray.<CodeBlock>create());
contextFile.getChildren().add(objectBlock);
CodeBlockImpl method1 = MockCodeBlockImpl
.make()
.setId("2")
.setBlockType(CodeBlock.Type.VALUE_FUNCTION)
.setName(METHOD_1)
.setStartLineNumber(0)
.setStartColumn(10)
.setEndLineNumber(0)
.setEndColumn(49)
.setChildren(JsoArray.<CodeBlock>create());
CodeBlockImpl method2 = MockCodeBlockImpl
.make()
.setId("3")
.setBlockType(CodeBlock.Type.VALUE_FUNCTION)
.setName(METHOD_2)
.setStartLineNumber(0)
.setStartColumn(50)
.setEndLineNumber(0)
.setEndColumn(LAST_COLUMN)
.setChildren(JsoArray.<CodeBlock>create());
objectBlock.getChildren().add(method1);
objectBlock.getChildren().add(method2);
CodeBlockImpl localVar = MockCodeBlockImpl
.make()
.setId("4")
.setBlockType(CodeBlock.Type.VALUE_FIELD)
.setName("var1")
.setStartLineNumber(0)
.setStartColumn(60)
.setEndLineNumber(0)
.setEndColumn(79)
.setChildren(JsoArray.<CodeBlock>create());
method2.getChildren().add(localVar);
CodeBlockImpl localVarField = MockCodeBlockImpl
.make()
.setId("5")
.setBlockType(CodeBlock.Type.VALUE_FIELD)
.setName("foo")
.setStartLineNumber(0)
.setStartColumn(65)
.setEndLineNumber(0)
.setEndColumn(74)
.setChildren(JsoArray.<CodeBlock>create());
localVar.getChildren().add(localVarField);
return contextFile;
}
/**
* Check that produced proposals are equal to the given ones.
* @param builder proposal producer
* @param expected expected proposal, concatenated with "," separator
* @param triggeringString context
* @param isThisContext flag indicating "this."-like previous context
* @return produced proposals (for deeper analysis)
*/
private JsonArray<AutocompleteProposal> checkProposals(ScopeTrieBuilder builder,
String[] expected, String triggeringString, boolean isThisContext) {
Position cursor = new Position(
Document.createEmpty().getFirstLineInfo(), triggeringString.length());
ProposalBuilder<State> proposalBuilder = new MockProposalBuilder();
CompletionContext<State> context = new CompletionContext<State>(
"", triggeringString, isThisContext, CompletionType.GLOBAL, null, 0);
JsonArray<AutocompleteProposal> proposals = proposalBuilder.doGetProposals(
context, cursor, builder);
assertEquals(JsonCollections.createStringSet(expected), TestUtils.createNameSet(proposals));
return proposals;
}
private ScopeTrieBuilder createScopeTrieBuilder(CodeBlock codeBlock) {
CodeFile codeFile = new CodeFile(path);
codeFile.setRootCodeBlock(codeBlock);
return new ScopeTrieBuilder(codeFile, SyntaxType.JS);
}
public void testEmptyDataSources() {
CodeFile codeFile = new CodeFile(path);
checkProposals(new ScopeTrieBuilder(codeFile, SyntaxType.JS), new String[0], "foo", false);
}
public void testExternalFileTopLevelProposals() {
CodeBlockImpl file1 = MockCodeBlockImpl.make().setBlockType(CodeBlock.Type.VALUE_FILE)
.setChildren(JsoArray.<CodeBlock>create())
.setId("0")
.setName("/file1.js");
file1.getChildren().add(MockCodeBlockImpl
.make()
.setId("1")
.setBlockType(CodeBlock.Type.VALUE_FUNCTION)
.setName("foobar")
.setStartLineNumber(0)
.setStartColumn(0)
.setEndLineNumber(0)
.setEndColumn(49));
file1.getChildren().add(MockCodeBlockImpl
.make()
.setId("2")
.setBlockType(CodeBlock.Type.VALUE_FUNCTION)
.setName("barbaz")
.setStartLineNumber(0)
.setStartColumn(0)
.setEndLineNumber(0)
.setEndColumn(49));
CodeBlockImpl file2 = MockCodeBlockImpl.make().setBlockType(CodeBlock.Type.VALUE_FILE)
.setChildren(JsoArray.<CodeBlock>create())
.setId("1")
.setName("/file2.js");
file2.getChildren().add(MockCodeBlockImpl
.make()
.setId("1")
.setBlockType(CodeBlock.Type.VALUE_FUNCTION)
.setName("foobaz")
.setStartLineNumber(0)
.setStartColumn(0)
.setEndLineNumber(0)
.setEndColumn(49));
file2.getChildren().add(MockCodeBlockImpl
.make()
.setId("2")
.setBlockType(CodeBlock.Type.VALUE_FUNCTION)
.setName("barfoo")
.setStartLineNumber(0)
.setStartColumn(0)
.setEndLineNumber(0)
.setEndColumn(49));
CodeFile codeFile = new CodeFile(path);
ScopeTrieBuilder builder = new ScopeTrieBuilder(codeFile, SyntaxType.JS);
JsoStringMap<CodeBlock> codeBlockMap = JsoStringMap.create();
codeBlockMap.put(file1.getName(), file1);
codeBlockMap.put(file2.getName(), file2);
builder.setCodeGraph(CodeGraphImpl.make().setCodeBlockMap(codeBlockMap));
JsonArray<AutocompleteProposal> proposals = checkProposals(
builder, new String[] {"foobar", "foobaz"}, "foo", false);
assertEquals(new PathUtil("/file1.js"),
TestUtils.findProposalByName(proposals, "foobar").getPath());
assertEquals(new PathUtil("/file2.js"),
TestUtils.findProposalByName(proposals, "foobaz").getPath());
checkProposals(builder, new String[] {"barbaz", "barfoo", "foobar", "foobaz"}, "", false);
// Check this proposals do not receive top-level items.
checkProposals(builder, new String[0], "", true);
}
public void testLexicalScopeCompletionIncludesAncestorScopesAndChildScopes() {
ScopeTrieBuilder builder = setupBuilder();
Position cursor = new Position(Document.createEmpty().getFirstLineInfo(), 82);
ProposalBuilder<State> proposalBuilder = new MockProposalBuilder();
CompletionContext<State> context = new CompletionContext<State>(
"", "", false, CompletionType.GLOBAL, null, 0);
JsonArray<AutocompleteProposal> proposals = proposalBuilder.doGetProposals(
context, cursor, builder);
JsonStringSet expected = JsonCollections.createStringSet(OBJECT_1, METHOD_2, METHOD_1, "var1");
assertEquals(expected, TestUtils.createNameSet(proposals));
}
public void testCaseInsensitiveSearch() {
assertTrue(Autocompleter.CASE_INSENSITIVE);
ScopeTrieBuilder builder = setupBuilder();
Position cursor = new Position(Document.createEmpty().getFirstLineInfo(), 82);
ProposalBuilder<State> proposalBuilder = new MockProposalBuilder();
CompletionContext<State> context = new CompletionContext<State>(
"", "MEtH", false, CompletionType.GLOBAL, null, 0);
JsonArray<AutocompleteProposal> proposals = proposalBuilder.doGetProposals(
context, cursor, builder);
JsonStringSet expected = JsonCollections.createStringSet("method2", "method1");
assertEquals(expected, TestUtils.createNameSet(proposals));
}
public void testThisCompletionIncludesDirectParentScope() {
ScopeTrieBuilder builder = setupBuilder();
Position cursor = new Position(Document.createEmpty().getFirstLineInfo(), 86);
ProposalBuilder<State> proposalBuilder = new MockProposalBuilder();
CompletionContext<State> context = new CompletionContext<State>(
"", "", true, CompletionType.PROPERTY, null, 0);
JsonArray<AutocompleteProposal> proposals = proposalBuilder.doGetProposals(
context, cursor, builder);
assertEquals(JsonCollections.createStringSet(METHOD_2, METHOD_1),
TestUtils.createNameSet(proposals));
}
public void testScopeEndBoundry() {
ScopeTrieBuilder builder = setupBuilder();
ProposalBuilder<State> proposalBuilder = new MockProposalBuilder();
CompletionContext<State> context = new CompletionContext<State>(
"", "", true, CompletionType.PROPERTY, null, 0);
Position cursor = new Position(Document.createEmpty().getFirstLineInfo(), LAST_COLUMN + 1);
assertFalse(proposalBuilder.doGetProposals(context, cursor, builder).isEmpty());
cursor = new Position(Document.createEmpty().getFirstLineInfo(), LAST_COLUMN + 2);
assertTrue(proposalBuilder.doGetProposals(context, cursor, builder).isEmpty());
}
/**
* Checks that even if we have problems with resolving scope, we try to
* search with raw "previousContext".
*/
public void testBareScopePrefixMinimum() {
ScopeTrieBuilder scopeTrieBuilder = new ScopeTrieBuilder(new CodeFile(path), SyntaxType.JS);
String previousContext = "moo.";
CompletionContext<State> context = new CompletionContext<State>(
previousContext, "", false, CompletionType.PROPERTY, null, 0);
Position cursor = new Position(Document.createEmpty().getFirstLineInfo(), 1);
JsoStringSet prefixes = scopeTrieBuilder.calculateScopePrefixes(context, cursor);
assertNotNull(prefixes);
assertFalse(prefixes.isEmpty());
assertTrue(prefixes.contains(previousContext));
}
/**
* Checks that for scoped position "full scope path + previous context" is
* included to prefix list.
*/
public void testFullLexicalScopePrefix() {
ScopeTrieBuilder builder = setupBuilder();
String previousContext = "moo.";
CompletionContext<State> context = new CompletionContext<State>(
previousContext, "", false, CompletionType.PROPERTY, null, 0);
Position cursor = new Position(Document.createEmpty().getFirstLineInfo(), 20);
JsoStringSet prefixes = builder.calculateScopePrefixes(context, cursor);
assertNotNull(prefixes);
assertFalse(prefixes.isEmpty());
assertTrue(prefixes.contains(OBJECT_1 + "." + METHOD_1 + "." + previousContext));
}
public void testScopeResolutionForExpandingContext() {
ScopeTrieBuilder builder = setupBuilder();
ProposalBuilder<State> proposalBuilder = new MockProposalBuilder();
CompletionContext<State> context = new CompletionContext<State>(
"", "", true, CompletionType.PROPERTY, null, 0);
Position cursor = new Position(Document.createEmpty().getFirstLineInfo(), LAST_COLUMN + 2);
assertTrue(proposalBuilder.doGetProposals(context, cursor, builder).isEmpty());
context = new CompletionContext<State>(
OBJECT_1 + ".", "", true, CompletionType.PROPERTY, null, 0);
cursor = new Position(Document.createEmpty().getFirstLineInfo(), LAST_COLUMN + 2);
assertFalse(proposalBuilder.doGetProposals(context, cursor, builder).isEmpty());
}
private ScopeTrieBuilder setupBuilder() {
CodeBlock contextFile = createCodeBlockTree();
JsoStringMap<CodeBlock> codeBlockMap = JsoStringMap.create();
codeBlockMap.put(contextFile.getName(), contextFile);
ScopeTrieBuilder builder = createScopeTrieBuilder(contextFile);
builder.setCodeGraph(CodeGraphImpl.make().setCodeBlockMap(codeBlockMap));
return builder;
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/codegraph/ExplicitAutocompleterTest.java | javatests/com/google/collide/client/code/autocomplete/codegraph/ExplicitAutocompleterTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.codegraph;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.collide.codemirror2.Token;
import com.google.collide.codemirror2.TokenType;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
/**
* Test cases for {@link ExplicitAutocompleter}.
*/
public class ExplicitAutocompleterTest extends SynchronousTestCase {
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
public void testCalculateClosingParens() {
JsonArray<Token> tokens = JsonCollections.createArray();
tokens.add(new Token("", TokenType.NULL, "{"));
tokens.add(new Token("", TokenType.NULL, "foo"));
tokens.add(new Token("", TokenType.NULL, "["));
tokens.add(new Token("", TokenType.NULL, "]"));
tokens.add(new Token("", TokenType.WHITESPACE, " "));
tokens.add(new Token("", TokenType.NULL, ")"));
tokens.add(new Token("", TokenType.NULL, "}"));
tokens.add(new Token("", TokenType.NULL, "bar"));
tokens.add(new Token("", TokenType.NULL, "]"));
tokens.add(new Token("", TokenType.NULL, "bar"));
//{foo[] )}bar]bar
//0123456789
assertEquals("", ExplicitAutocompleter.calculateClosingParens(tokens, 4));
assertEquals("])}", ExplicitAutocompleter.calculateClosingParens(tokens, 5));
assertEquals(")}", ExplicitAutocompleter.calculateClosingParens(tokens, 6));
}
public void testCalculateOpenParens() {
JsonArray<Token> tokens = JsonCollections.createArray();
tokens.add(new Token("", TokenType.NULL, "{"));
tokens.add(new Token("", TokenType.NULL, "foo"));
tokens.add(new Token("", TokenType.NULL, "["));
tokens.add(new Token("", TokenType.NULL, "moo"));
tokens.add(new Token("", TokenType.NULL, "("));
tokens.add(new Token("", TokenType.WHITESPACE, " "));
tokens.add(new Token("", TokenType.NULL, ")"));
tokens.add(new Token("", TokenType.WHITESPACE, " "));
tokens.add(new Token("", TokenType.NULL, "{"));
tokens.add(new Token("", TokenType.NULL, "]"));
tokens.add(new Token("", TokenType.WHITESPACE, " "));
tokens.add(new Token("", TokenType.NULL, ")"));
tokens.add(new Token("", TokenType.NULL, "("));
//{foo[moo( ) {] ](
//012345678901234567
assertEquals("", ExplicitAutocompleter.calculateOpenParens(tokens, 0));
assertEquals("}", ExplicitAutocompleter.calculateOpenParens(tokens, 1));
assertEquals("}", ExplicitAutocompleter.calculateOpenParens(tokens, 2));
assertEquals("]}", ExplicitAutocompleter.calculateOpenParens(tokens, 5));
assertEquals(")]}", ExplicitAutocompleter.calculateOpenParens(tokens, 9));
assertEquals("]}", ExplicitAutocompleter.calculateOpenParens(tokens, 11));
assertEquals("}]}", ExplicitAutocompleter.calculateOpenParens(tokens, 13));
assertEquals("", ExplicitAutocompleter.calculateOpenParens(tokens, 14));
assertEquals("", ExplicitAutocompleter.calculateOpenParens(tokens, 16));
assertEquals(")", ExplicitAutocompleter.calculateOpenParens(tokens, 17));
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/codegraph/CommentSelectionTest.java | javatests/com/google/collide/client/code/autocomplete/codegraph/CommentSelectionTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.codegraph;
import com.google.collide.client.code.autocomplete.MockAutocompleterEnvironment;
import com.google.collide.client.code.lang.LanguageHelperResolver;
import com.google.collide.client.editor.Editor;
import com.google.collide.client.editor.input.TestSignalEvent;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.collide.client.testutil.TestSchedulerImpl;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.util.input.ModifierKeys;
import com.google.collide.codemirror2.SyntaxType;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.document.LineFinder;
import com.google.collide.shared.document.Position;
import com.google.collide.shared.util.JsonCollections;
import com.google.gwt.core.client.Scheduler;
import elemental.events.KeyboardEvent;
import org.waveprotocol.wave.client.common.util.SignalEvent;
/**
* Test cases for comment/uncomment selection feature.
*
*/
public class CommentSelectionTest extends SynchronousTestCase {
@Override
public String getModuleName() {
return "com.google.cofllide.client.TestCode";
}
public void testSingleLastLineComment() {
String text = "com<cursor>ment me";
String expected = "//com<cursor>ment me";
checkCommentSelection(text, expected, 0, 3, 0, 3, 0, 5, 0, 5);
}
public void testSingleLastLineUnComment() {
String text = "//com<cursor>ment me";
String expected = "com<cursor>ment me";
checkCommentSelection(text, expected, 0, 5, 0, 5, 0, 3, 0, 3);
}
public void testSingleCommentNextLineIsLong() {
String text = "com<old cursor>ment me\ncom<new cursor>ment me";
String expected = "//com<old cursor>ment me\ncom<new cursor>ment me";
checkCommentSelection(text, expected, 0, 3, 0, 3, 1, 3, 1, 3);
}
public void testSingleCommentNextLineIsShort() {
String text = "blah-blah com*ment me\n..*";
String expected = "//blah-blah com*ment me\n..*";
checkCommentSelection(text, expected, 0, 13, 0, 13, 1, 3, 1, 3);
}
public void testSingleCommentAtLineStart() {
String text = "comment me\nblah-blah";
String expected = "//comment me\nblah-blah";
checkCommentSelection(text, expected, 0, 0, 0, 0, 1, 0, 1, 0);
}
public void testCommentMultiFromMidLineToDocEnd() {
String text = "first\nsecond";
String expected = "//first\n//second";
checkCommentSelection(text, expected, 0, 3, 1, 6, 0, 5, 1, 8);
}
public void testCommentMultiFromStartLineToStartLine() {
String text = "first\nsecond";
String expected = "//first\nsecond";
checkCommentSelection(text, expected, 0, 0, 1, 0, 0, 0, 1, 0);
}
public void testUnCommentMultiFromMidLineToMidLine() {
String text = "//first\n//second";
String expected = "first\nsecond";
checkCommentSelection(text, expected, 0, 5, 1, 4, 0, 3, 1, 2);
}
public void testCommentMultiMixed() {
String text = "//first\nsecond\n//third\n";
String expected = "////first\n//second\n////third\n";
checkCommentSelection(text, expected, 0, 0, 3, 0, 0, 0, 3, 0);
}
private void checkCommentSelection(
String text, String expected, int line1, int column1, int line2, int column2,
int expectedLine1, int expectedColumn1, int expectedLine2, int expectedColumn2) {
MockAutocompleterEnvironment helper = new MockAutocompleterEnvironment();
helper.setup(new PathUtil("test.js"), text, line1, column1, false);
final Editor editor = helper.editor;
editor.getInput().getActionExecutor().addDelegate(
LanguageHelperResolver.getHelper(SyntaxType.JS).getActionExecutor());
LineFinder lineFinder = editor.getDocument().getLineFinder();
editor.getSelection().setSelection(
lineFinder.findLine(line1), column1, lineFinder.findLine(line2), column2);
final JsonArray<Scheduler.ScheduledCommand> scheduled = JsonCollections.createArray();
TestSchedulerImpl.AngryScheduler scheduler = new TestSchedulerImpl.AngryScheduler() {
@Override
public void scheduleDeferred(ScheduledCommand scheduledCommand) {
scheduled.add(scheduledCommand);
}
};
final TestSignalEvent ctrlSlashTriger = new TestSignalEvent(
KeyboardEvent.KeyCode.SLASH, SignalEvent.KeySignalType.INPUT,
ModifierKeys.ACTION);
Runnable ctrlShiftSlashClicker = new Runnable() {
@Override
public void run() {
editor.getInput().processSignalEvent(ctrlSlashTriger);
}
};
TestSchedulerImpl.runWithSpecificScheduler(ctrlShiftSlashClicker, scheduler);
while (!scheduled.isEmpty()) {
Scheduler.ScheduledCommand command = scheduled.remove(0);
command.execute();
}
String result = editor.getDocument().asText();
assertEquals("textual result", expected, result);
Position[] selectionRange = editor.getSelection().getSelectionRange(false);
assertEquals("selection start line", expectedLine1, selectionRange[0].getLineNumber());
assertEquals("selection start column", expectedColumn1, selectionRange[0].getColumn());
assertEquals("selection end line", expectedLine2, selectionRange[1].getLineNumber());
assertEquals("selection end column", expectedColumn2, selectionRange[1].getColumn());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/codegraph/CodeFileTest.java | javatests/com/google/collide/client/code/autocomplete/codegraph/CodeFileTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.codegraph;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.collide.client.util.PathUtil;
import com.google.collide.dto.CodeBlock;
import com.google.collide.dto.client.DtoClientImpls.CodeBlockImpl;
import com.google.collide.dto.client.DtoClientImpls.MockCodeBlockImpl;
import com.google.collide.json.client.JsoArray;
/**
*/
public class CodeFileTest extends SynchronousTestCase {
private static void assertScopeBounds(
int beginLine, int beginCol, int endLine, int endCol, Scope scope) {
assertEquals(beginLine, scope.getBeginLineNumber());
assertEquals(beginCol, scope.getBeginColumn());
assertEquals(endLine, scope.getEndLineNumber());
assertEquals(endCol, scope.getEndColumn());
}
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
public void testLexicalScopeAndObjectScopeAreTheSame() {
/*
* Something like var foobar = { foo: function() {}, bar: function() {} }
*/
CodeBlockImpl fnFoo = MockCodeBlockImpl
.make()
.setBlockType(CodeBlock.Type.VALUE_FUNCTION)
.setName("foo")
.setChildren(JsoArray.<CodeBlock>create())
.setStartLineNumber(1)
.setStartColumn(2)
.setEndLineNumber(1)
.setEndColumn(19);
CodeBlockImpl fnBar = MockCodeBlockImpl
.make()
.setBlockType(CodeBlock.Type.VALUE_FUNCTION)
.setName("bar")
.setChildren(JsoArray.<CodeBlock>create())
.setStartLineNumber(2)
.setStartColumn(2)
.setEndLineNumber(2)
.setEndColumn(19);
CodeBlockImpl varFoobar = MockCodeBlockImpl
.make()
.setBlockType(CodeBlock.Type.VALUE_FIELD)
.setName("foobar")
.setChildren(JsoArray.<CodeBlock>from(fnFoo, fnBar))
.setStartLineNumber(0)
.setStartColumn(0)
.setEndLineNumber(3)
.setEndColumn(0);
CodeBlockImpl fileCodeBlock = MockCodeBlockImpl
.make()
.setBlockType(CodeBlock.Type.VALUE_FILE)
.setChildren(JsoArray.<CodeBlock>from(varFoobar))
.setStartLineNumber(0)
.setStartColumn(0)
.setEndLineNumber(3)
.setEndColumn(0);
CodeFile codeFile = new CodeFile(new PathUtil("/foobar.js"));
codeFile.setRootCodeBlock(fileCodeBlock);
assertEquals(1, codeFile.getRootScope().getSubscopes().size());
assertEquals(2, codeFile.getRootScope().getSubscopes().get(0).getSubscopes().size());
assertScopeBounds(0, 0, 3, 0, codeFile.getRootScope());
assertScopeBounds(0, 0, 3, 0, codeFile.getRootScope().getSubscopes().get(0));
assertScopeBounds(
1, 2, 1, 19, codeFile.getRootScope().getSubscopes().get(0).getSubscopes().get(0));
assertScopeBounds(
2, 2, 2, 19, codeFile.getRootScope().getSubscopes().get(0).getSubscopes().get(1));
}
public void testLexicalScopeAndObjectScopeAreDifferent() {
/*
* Something like var foobar = { foo: function() {} }
*
* foobar.bar = function() { }
*/
CodeBlockImpl fnFoo = MockCodeBlockImpl
.make()
.setBlockType(CodeBlock.Type.VALUE_FUNCTION)
.setName("foo")
.setChildren(JsoArray.<CodeBlock>create())
.setStartLineNumber(1)
.setStartColumn(2)
.setEndLineNumber(1)
.setEndColumn(19);
CodeBlockImpl fnBar = MockCodeBlockImpl
.make()
.setBlockType(CodeBlock.Type.VALUE_FUNCTION)
.setName("bar")
.setChildren(JsoArray.<CodeBlock>create())
.setStartLineNumber(4)
.setStartColumn(24)
.setEndLineNumber(5)
.setEndColumn(0);
CodeBlockImpl varFoobar = MockCodeBlockImpl
.make()
.setBlockType(CodeBlock.Type.VALUE_FIELD)
.setName("foobar")
.setChildren(JsoArray.<CodeBlock>from(fnFoo, fnBar))
.setStartLineNumber(0)
.setStartColumn(0)
.setEndLineNumber(2)
.setEndColumn(0);
CodeBlockImpl fileCodeBlock = MockCodeBlockImpl
.make()
.setBlockType(CodeBlock.Type.VALUE_FILE)
.setChildren(JsoArray.<CodeBlock>from(varFoobar))
.setStartLineNumber(0)
.setStartColumn(0)
.setEndLineNumber(5)
.setEndColumn(0);
CodeFile codeFile = new CodeFile(new PathUtil("/foobar.js"));
codeFile.setRootCodeBlock(fileCodeBlock);
assertEquals(2, codeFile.getRootScope().getSubscopes().size());
assertEquals(1, codeFile.getRootScope().getSubscopes().get(0).getSubscopes().size());
assertScopeBounds(0, 0, 5, 0, codeFile.getRootScope());
assertScopeBounds(0, 0, 2, 0, codeFile.getRootScope().getSubscopes().get(0));
assertScopeBounds(4, 24, 5, 0, codeFile.getRootScope().getSubscopes().get(1));
assertScopeBounds(
1, 2, 1, 19, codeFile.getRootScope().getSubscopes().get(0).getSubscopes().get(0));
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/codegraph/CodeGraphSourceTest.java | javatests/com/google/collide/client/code/autocomplete/codegraph/CodeGraphSourceTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.codegraph;
import static com.google.collide.client.codeunderstanding.CodeGraphTestUtils.createCodeBlock;
import static com.google.collide.client.codeunderstanding.CodeGraphTestUtils.createCodeGraph;
import static com.google.collide.client.codeunderstanding.CodeGraphTestUtils.createFreshness;
import static com.google.collide.client.codeunderstanding.CodeGraphTestUtils.createTypeAssociation;
import com.google.collide.client.code.autocomplete.TestUtils;
import com.google.collide.client.codeunderstanding.CodeGraphTestUtils.MockCubeClient;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.collide.codemirror2.SyntaxType;
import com.google.collide.dto.CodeBlock;
import com.google.collide.dto.TypeAssociation;
import com.google.collide.dto.client.DtoClientImpls;
import com.google.collide.dto.client.DtoClientImpls.CodeBlockImpl;
import com.google.collide.dto.client.DtoClientImpls.CodeGraphImpl;
import com.google.collide.dto.client.DtoClientImpls.CodeGraphResponseImpl;
import com.google.collide.json.client.Jso;
import com.google.collide.json.client.JsoArray;
import com.google.collide.shared.util.JsonCollections;
/**
* Test for CodeGraphSource.
*
*/
public class CodeGraphSourceTest extends SynchronousTestCase {
@Override
public String getModuleName() {
return "com.google.collide.client.code.autocomplete.codegraph.CodeGraphTestModule";
}
private static class UpdateReceiver implements Runnable {
int runCount;
@Override
public void run() {
runCount++;
}
}
public void testFreshFileTreeWontDestroyLinks() {
CodeGraphResponseImpl response = DtoClientImpls.MockCodeGraphResponseImpl.make();
response.setFreshness(createFreshness("0", "1", "1"));
{
CodeBlock fileBlock = createCodeBlock("0", "/foo.js", CodeBlock.Type.FILE, 0, 0, 10, 0);
CodeBlock foo = createCodeBlock(fileBlock, "1", "foo", CodeBlock.Type.FIELD, 0, 0, 1, 0);
CodeBlock bar = createCodeBlock(fileBlock, "2", "bar", CodeBlock.Type.FIELD, 1, 0, 2, 0);
createCodeBlock(fileBlock, "3", "bar.doThis", CodeBlock.Type.FUNCTION, 1, 10, 2, 0);
TypeAssociation typeLink = createTypeAssociation(fileBlock, foo, fileBlock, bar);
CodeGraphImpl codeGraph = createCodeGraph(fileBlock);
codeGraph.setTypeAssociations(JsoArray.<TypeAssociation>from(typeLink));
response.setFullGraphJson(codeGraph.serialize());
}
{
CodeBlockImpl freshFileBlock = createCodeBlock(
"1", "/foo.js", CodeBlock.Type.FILE, 0, 0, 10, 0);
createCodeBlock(freshFileBlock, "1", "foo", CodeBlock.Type.FIELD, 0, 0, 1, 0);
createCodeBlock(freshFileBlock, "2", "foo.baz", CodeBlock.Type.FIELD, 1, 0, 2, 0);
createCodeBlock(freshFileBlock, "3", "bar", CodeBlock.Type.FIELD, 2, 0, 3, 0);
createCodeBlock(freshFileBlock, "4", "bar.doThis", CodeBlock.Type.FUNCTION, 2, 10, 3, 0);
response.setFileTreeJson(Jso.serialize(freshFileBlock));
}
MockCubeClient cubeClient = MockCubeClient.create();
UpdateReceiver updateListener = new UpdateReceiver();
CodeGraphSource codeGraphSource = new CodeGraphSource(cubeClient, updateListener);
codeGraphSource.setPaused(false);
// This will immediately fire api call
cubeClient.setPath("/foo.js");
try {
assertEquals("one api call after setDocument", 1, cubeClient.api.collectedCallbacks.size());
cubeClient.api.collectedCallbacks.get(0).onMessageReceived(response);
} finally {
cubeClient.cleanup();
}
assertEquals("one update after data received", 1, updateListener.runCount);
assertTrue("codeGraphSource received update", codeGraphSource.hasUpdate());
CodeGraphPrefixIndex prefixIndex = new CodeGraphPrefixIndex(
codeGraphSource.constructCodeGraph(), SyntaxType.JS);
assertEquals("search in updated trie", JsonCollections.createStringSet("foo.baz", "foo.doThis"),
TestUtils.createNameSet(prefixIndex.search("foo.")));
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/codegraph/CodeGraphPrefixIndexTest.java | javatests/com/google/collide/client/code/autocomplete/codegraph/CodeGraphPrefixIndexTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.codegraph;
import static com.google.collide.client.codeunderstanding.CodeGraphTestUtils.createCodeBlock;
import static com.google.collide.client.codeunderstanding.CodeGraphTestUtils.createInheritanceAssociation;
import static com.google.collide.client.codeunderstanding.CodeGraphTestUtils.createRootImportAssociation;
import static com.google.collide.client.codeunderstanding.CodeGraphTestUtils.createTypeAssociation;
import com.google.collide.client.code.autocomplete.TestUtils;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.collide.client.util.PathUtil;
import com.google.collide.codemirror2.SyntaxType;
import com.google.collide.dto.CodeBlock;
import com.google.collide.dto.ImportAssociation;
import com.google.collide.dto.client.DtoClientImpls.CodeGraphImpl;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.client.JsoStringMap;
import com.google.collide.shared.util.JsonCollections;
import org.junit.Ignore;
/**
* Tests for code block => autocomplete proposal translator.
*/
public class CodeGraphPrefixIndexTest extends SynchronousTestCase {
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
public void testCaseInsensitiveSearch() {
CodeBlock fileBar = createCodeBlock("1", "/bar.js", CodeBlock.Type.FILE, 0, 0, 0, 99);
CodeBlock varBar = createCodeBlock(fileBar, "11", "Bar", CodeBlock.Type.FIELD, 0, 0, 0, 99);
createCodeBlock(fileBar, "12", "doThis", CodeBlock.Type.FUNCTION, 1, 0, 10, 99);
createCodeBlock(fileBar, "13", "doThat", CodeBlock.Type.FUNCTION, 11, 0, 20, 99);
JsoStringMap<CodeBlock> files = JsoStringMap.<CodeBlock>create();
files.put(fileBar.getName(), fileBar);
CodeGraphImpl codeGraph = CodeGraphImpl.make();
codeGraph.setCodeBlockMap(files);
CodeGraphPrefixIndex prefixIndex = new CodeGraphPrefixIndex(codeGraph, SyntaxType.JS);
assertEquals(JsonCollections.createStringSet("doThat", "doThis"),
TestUtils.createNameSet(prefixIndex.search("dot")));
}
public void testTypeAssociations() {
/*
* /bar.js:
*
* Bar {
* doThis: function() {},
* doThat: function() {}
* }
*/
CodeBlock fileBar = createCodeBlock("1", "/bar.js", CodeBlock.Type.FILE, 0, 0, 0, 99);
CodeBlock varBar = createCodeBlock(fileBar, "11", "Bar", CodeBlock.Type.FIELD, 0, 0, 0, 99);
createCodeBlock(fileBar, "12", "Bar.doThis", CodeBlock.Type.FUNCTION, 1, 0, 10, 99);
createCodeBlock(fileBar, "13", "Bar.doThat", CodeBlock.Type.FUNCTION, 11, 0, 20, 99);
/*
* /foo.js:
*
* // @type {Bar}
* var Foo;
*/
CodeBlock fileFoo = createCodeBlock("0", "/foo.js", CodeBlock.Type.FILE, 0, 0, 0, 99);
CodeBlock varFoo = createCodeBlock("11", "Foo", CodeBlock.Type.FIELD, 0, 0, 0, 99);
fileFoo.getChildren().add(varFoo);
JsoStringMap<CodeBlock> files = JsoStringMap.<CodeBlock>create();
files.put(fileBar.getName(), fileBar);
files.put(fileFoo.getName(), fileFoo);
CodeGraphImpl codeGraph = CodeGraphImpl.make();
codeGraph.setCodeBlockMap(files);
codeGraph.setTypeAssociations(JsoArray.from(
createTypeAssociation(fileFoo, varFoo, fileBar, varBar)));
CodeGraphPrefixIndex prefixIndex = new CodeGraphPrefixIndex(codeGraph, SyntaxType.JS);
assertEquals(JsonCollections.createStringSet("Foo.doThat", "Foo.doThis"),
TestUtils.createNameSet(prefixIndex.search("Foo.")));
}
@Ignore
public void testTypeAssociationChain() {
CodeBlock fileFoo = createCodeBlock("0", "/foo.js", CodeBlock.Type.FILE, 0, 0, 99, 0);
createCodeBlock(fileFoo, "11", "Foo", CodeBlock.Type.FIELD, 0, 0, 99, 0);
CodeBlock typeFoo = createCodeBlock(
fileFoo, "12", "Foo.prototype", CodeBlock.Type.FIELD, 0, 0, 99, 0);
createCodeBlock(fileFoo, "13", "Foo.prototype.doThis", CodeBlock.Type.FUNCTION, 11, 0, 20, 0);
CodeBlock fileBar = createCodeBlock("1", "/bar.js", CodeBlock.Type.FILE, 0, 0, 10, 0);
createCodeBlock(fileBar, "11", "Bar", CodeBlock.Type.FIELD, 0, 0, 1, 0);
CodeBlock typeBar = createCodeBlock(
fileBar, "12", "Bar.prototype", CodeBlock.Type.FIELD, 0, 4, 1, 0);
CodeBlock fieldFoo = createCodeBlock(
fileBar, "13", "Bar.prototype.foo", CodeBlock.Type.FIELD, 0, 14, 1, 0);
CodeBlock varBaz = createCodeBlock(fileBar, "14", "baz", CodeBlock.Type.FIELD, 5, 0, 6, 0);
JsoStringMap<CodeBlock> files = JsoStringMap.<CodeBlock>create();
files.put(fileBar.getName(), fileBar);
files.put(fileFoo.getName(), fileFoo);
CodeGraphImpl codeGraph = CodeGraphImpl.make();
codeGraph.setCodeBlockMap(files);
codeGraph.setTypeAssociations(JsoArray.from(
createTypeAssociation(fileBar, varBaz, fileBar, typeBar),
createTypeAssociation(fileBar, fieldFoo, fileFoo, typeFoo)));
CodeGraphPrefixIndex prefixIndex = new CodeGraphPrefixIndex(codeGraph, SyntaxType.JS);
assertEquals(JsonCollections.createStringSet("baz.foo.doThis"),
TestUtils.createNameSet(prefixIndex.search("baz.foo.")));
}
public void testMultipleLinkRepresentatives() {
/*
* /window.js:
*
* Window.prototype.doThis = function() {}
*/
CodeBlock fileWindow = createCodeBlock("1", "/bar.js", CodeBlock.Type.FILE, 0, 0, 0, 99);
createCodeBlock(fileWindow, "11", "Window", CodeBlock.Type.FIELD, 0, 0, 0, 99);
CodeBlock typeWindow = createCodeBlock(fileWindow, "12", "Window.prototype",
CodeBlock.Type.FIELD, 0, 0, 0, 99);
createCodeBlock(fileWindow, "13", "Window.prototype.doThis",
CodeBlock.Type.FUNCTION, 0, 0, 0, 99);
/*
* /jquery.js:
*
* Window.prototype.doThat = function() {}
*/
CodeBlock fileJquery = createCodeBlock("0", "/jquery.js", CodeBlock.Type.FILE, 0, 0, 0, 99);
CodeBlock varJqueryWindow = createCodeBlock(fileJquery, "11", "Window",
CodeBlock.Type.FIELD, 0, 0, 0, 99);
createCodeBlock(fileJquery, "12", "Window.prototype",
CodeBlock.Type.FIELD, 0, 0, 0, 99);
createCodeBlock(fileJquery, "13", "Window.prototype.doThat",
CodeBlock.Type.FUNCTION, 0, 0, 0, 99);
/*
* /decl.js:
*
* // @type{Window}
* var top;
*/
CodeBlock fileDecl = createCodeBlock("2", "/decl.js", CodeBlock.Type.FILE, 0, 0, 0, 99);
CodeBlock varWindow = createCodeBlock(fileDecl, "11", "top",
CodeBlock.Type.FIELD, 0, 0, 0, 99);
JsoStringMap<CodeBlock> files = JsoStringMap.<CodeBlock>create();
files.put(fileWindow.getName(), fileWindow);
files.put(fileJquery.getName(), fileJquery);
files.put(fileDecl.getName(), fileDecl);
CodeGraphImpl codeGraph = CodeGraphImpl.make();
codeGraph.setCodeBlockMap(files);
codeGraph.setTypeAssociations(JsoArray.from(
createTypeAssociation(fileDecl, varWindow, fileWindow, typeWindow)));
CodeGraphPrefixIndex prefixIndex = new CodeGraphPrefixIndex(codeGraph, SyntaxType.JS);
assertEquals(JsonCollections.createStringSet("top.doThat", "top.doThis"),
TestUtils.createNameSet(prefixIndex.search("top.")));
}
public void testInheritanceAssociations() {
/*
* /bar.js:
*
* function Bar() {};
* Bar.prototype.doThis = function() {};
* Bar.prototype.doThat = function() {};
*
* // @extends {Bar}
* function Foo() {};
* Foo.prototype.doThird = function() {};
*/
CodeBlock fileBar = createCodeBlock("1", "/bar.js", CodeBlock.Type.FILE, 0, 0, 0, 99);
createCodeBlock(fileBar, "11", "Bar", CodeBlock.Type.FUNCTION, 0, 0, 0, 99);
CodeBlock prototypeBar = createCodeBlock(
fileBar, "12", "Bar.prototype", CodeBlock.Type.FIELD, 0, 0, 0, 99);
createCodeBlock(fileBar, "13", "Bar.prototype.doThis", CodeBlock.Type.FUNCTION, 1, 0, 10, 99);
createCodeBlock(fileBar, "14", "Bar.prototype.doThat", CodeBlock.Type.FUNCTION, 11, 0, 20, 99);
createCodeBlock(fileBar, "15", "Foo", CodeBlock.Type.FUNCTION, 100, 0, 199, 99);
CodeBlock prototypeFoo = createCodeBlock(
fileBar, "16", "Foo.prototype", CodeBlock.Type.FIELD, 100, 0, 199, 99);
createCodeBlock(
fileBar, "17", "Foo.prototype.doThird", CodeBlock.Type.FUNCTION, 101, 0, 120, 99);
JsoStringMap<CodeBlock> files = JsoStringMap.<CodeBlock>create();
files.put(fileBar.getName(), fileBar);
CodeGraphImpl codeGraph = CodeGraphImpl.make();
codeGraph.setCodeBlockMap(files);
codeGraph.setInheritanceAssociations(JsoArray.from(
createInheritanceAssociation(fileBar, prototypeFoo, fileBar, prototypeBar)));
CodeGraphPrefixIndex prefixIndex = new CodeGraphPrefixIndex(codeGraph, SyntaxType.JS);
assertEquals(JsonCollections.createStringSet(
"Foo.prototype.doThird", "Foo.prototype.doThis", "Foo.prototype.doThat"),
TestUtils.createNameSet(prefixIndex.search("Foo.prototype.")));
}
public void testRootImportAssociation() {
/*
* /lib.py:
*
* def foo:
* return 42;
*/
CodeBlock fileLib = createCodeBlock("1", "/lib.py", CodeBlock.Type.FILE, 0, 0, 0, 99);
CodeBlock funFoo = createCodeBlock(fileLib, "11", "foo", CodeBlock.Type.FUNCTION, 0, 0, 0, 99);
/*
* /api/ext/util.py:
*
* def bar:
* return None;
*/
CodeBlock fileUtil = createCodeBlock("2", "/api/ext/util.py", CodeBlock.Type.FILE, 0, 0, 0, 99);
CodeBlock funBar = createCodeBlock(fileUtil, "11", "bar", CodeBlock.Type.FUNCTION, 0, 0, 0, 99);
/*
* /main.py:
*
* import lib
* from api.ext import util
*/
CodeBlock fileMain = createCodeBlock("3", "/main.py", CodeBlock.Type.FILE, 0, 0, 0, 99);
ImportAssociation importLib = createRootImportAssociation(fileMain, fileLib);
ImportAssociation importUtil = createRootImportAssociation(fileMain, fileUtil);
JsoStringMap<CodeBlock> files = JsoStringMap.<CodeBlock>create();
files.put(fileLib.getId(), fileLib);
files.put(fileMain.getId(), fileMain);
files.put(fileUtil.getId(), fileUtil);
CodeGraphImpl codeGraph = CodeGraphImpl.make();
codeGraph.setCodeBlockMap(files);
codeGraph.setImportAssociations(JsoArray.from(importLib, importUtil));
CodeGraphPrefixIndex prefixIndex = new CodeGraphPrefixIndex(codeGraph, SyntaxType.PY);
assertEquals(JsonCollections.createStringSet("lib.foo"),
TestUtils.createNameSet(prefixIndex.search("lib.f")));
assertEquals(JsonCollections.createStringSet("util.bar"),
TestUtils.createNameSet(prefixIndex.search("util.")));
}
public void testNoGlobalNamespace() {
/*
* /file1.py:
*
* def foo1:
* return 42;
*/
CodeBlock file1 = createCodeBlock("1", "/file1.py", CodeBlock.Type.FILE, 0, 0, 0, 99);
CodeBlock funFoo1 = createCodeBlock(file1, "11", "foo1", CodeBlock.Type.FUNCTION, 0, 0, 0, 99);
/*
* /file2.py:
*
* def foo2:
* return 24;
*/
CodeBlock file2 = createCodeBlock("2", "/file2.py", CodeBlock.Type.FILE, 0, 0, 0, 99);
CodeBlock funFoo2 = createCodeBlock(file2, "21", "foo2", CodeBlock.Type.FUNCTION, 0, 0, 0, 99);
JsoStringMap<CodeBlock> files = JsoStringMap.<CodeBlock>create();
files.put(file1.getId(), file1);
files.put(file2.getId(), file2);
CodeGraphImpl codeGraph = CodeGraphImpl.make();
codeGraph.setCodeBlockMap(files);
CodeGraphPrefixIndex prefixIndex = new CodeGraphPrefixIndex(
codeGraph, SyntaxType.PY, new PathUtil("/file1.py"));
assertEquals(JsonCollections.createStringSet("foo1"),
TestUtils.createNameSet(prefixIndex.search("f")));
}
public void testFilesWithSameName() {
/*
* /file1.py:
*
* def foo1:
* return 1;
*
* def foo3:
* return 3;
*/
CodeBlock file1a = createCodeBlock("1", "/file1.py", CodeBlock.Type.FILE, 0, 0, 3, 0);
CodeBlock funFoo1a = createCodeBlock(
file1a, "11", "foo1", CodeBlock.Type.FIELD, 0, 0, 1, 0);
CodeBlock funFoo3 = createCodeBlock(
file1a, "11", "foo3", CodeBlock.Type.FIELD, 1, 0, 2, 0);
/*
* /file1.py:
*
* def foo1:
* return 1;
*
* def foo2:
* return 2;
*/
CodeBlock file1b = createCodeBlock("2", "/file1.py", CodeBlock.Type.FILE, 0, 0, 3, 0);
CodeBlock funFoo1b = createCodeBlock(
file1b, "21", "foo1", CodeBlock.Type.FUNCTION, 0, 0, 0, 99);
CodeBlock funFoo2 = createCodeBlock(
file1b, "22", "foo2", CodeBlock.Type.FUNCTION, 1, 0, 1, 99);
JsoStringMap<CodeBlock> files = JsoStringMap.<CodeBlock>create();
files.put(file1a.getId(), file1a);
files.put(file1b.getId(), file1b);
CodeGraphImpl codeGraph = CodeGraphImpl.make();
codeGraph.setCodeBlockMap(files);
CodeGraphPrefixIndex prefixIndex = new CodeGraphPrefixIndex(
codeGraph, SyntaxType.PY, new PathUtil("/file1.py"));
assertEquals(JsonCollections.createStringSet("foo1", "foo2", "foo3"),
TestUtils.createNameSet(prefixIndex.search("f")));
}
public void testPackages() {
CodeBlock defaultPackage = createCodeBlock("p1", "", CodeBlock.Type.PACKAGE, 0, 0, 0, 0);
CodeBlock pkgGoogle = createCodeBlock(
defaultPackage, "p2", "google", CodeBlock.Type.PACKAGE, 0, 0, 0, 0);
CodeBlock pkgAppengine = createCodeBlock(
defaultPackage, "p3", "google.appengine", CodeBlock.Type.PACKAGE, 0, 0, 0, 0);
CodeBlock pkgExt = createCodeBlock(
defaultPackage, "p4", "google.ext", CodeBlock.Type.PACKAGE, 0, 0, 0, 0);
CodeGraphImpl codeGraph = CodeGraphImpl.make();
codeGraph.setDefaultPackage(defaultPackage);
codeGraph.setCodeBlockMap(JsoStringMap.<CodeBlock>create());
CodeGraphPrefixIndex prefixIndex = new CodeGraphPrefixIndex(codeGraph, SyntaxType.PY);
assertEquals(JsonCollections.createStringSet("google"),
TestUtils.createNameSet(prefixIndex.search("goo")));
assertEquals(JsonCollections.createStringSet("google.appengine", "google.ext"),
TestUtils.createNameSet(prefixIndex.search("google.")));
assertEquals(JsonCollections.createStringSet("google.appengine"),
TestUtils.createNameSet(prefixIndex.search("google.a")));
assertEquals(JsonCollections.createStringSet("google.ext"),
TestUtils.createNameSet(prefixIndex.search("google.e")));
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/codegraph/CodeGraphAutocompleterTest.java | javatests/com/google/collide/client/code/autocomplete/codegraph/CodeGraphAutocompleterTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.codegraph;
import static com.google.collide.client.code.autocomplete.TestUtils.CTRL_SPACE;
import static com.google.collide.codemirror2.TokenType.NULL;
import com.google.collide.client.code.autocomplete.AbstractTrie;
import com.google.collide.client.code.autocomplete.AutocompleteProposal;
import com.google.collide.client.code.autocomplete.AutocompleteProposals.Context;
import com.google.collide.client.code.autocomplete.AutocompleteProposals.ProposalWithContext;
import com.google.collide.client.code.autocomplete.AutocompleteResult;
import com.google.collide.client.code.autocomplete.DefaultAutocompleteResult;
import com.google.collide.client.code.autocomplete.MockAutocompleterEnvironment;
import com.google.collide.client.code.autocomplete.PrefixIndex;
import com.google.collide.client.code.autocomplete.TestUtils;
import com.google.collide.client.documentparser.DocumentParser;
import com.google.collide.client.documentparser.ParseResult;
import com.google.collide.client.editor.selection.SelectionModel;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.util.collections.SkipListStringBag;
import com.google.collide.codemirror2.State;
import com.google.collide.codemirror2.SyntaxType;
import com.google.collide.codemirror2.Token;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringSet;
import com.google.collide.shared.util.JsonCollections;
/**
* Tests for JavaScript autocompletion.
*
*/
public class CodeGraphAutocompleterTest extends SynchronousTestCase {
/**
* The simplest completion context implementation.
*/
static class MockProposalBuilder extends ProposalBuilder<State> {
@Override
public CompletionContext<State> buildContext(
SelectionModel selection, DocumentParser parser) {
JsonArray<Token> tokens = JsonCollections.createArray();
State state = TestUtils.createMockState();
tokens.add(new Token(null, NULL, ""));
ParseResult<State> parseResult = new ParseResult<State>(tokens, state) {};
return buildContext(
new ParseUtils.ExtendedParseResult<State>(parseResult, ParseUtils.Context.IN_CODE));
}
public MockProposalBuilder() {
super(State.class);
}
@Override
protected void addShortcutsTo(CompletionContext<State> context, JsonStringSet prefixes) {
}
@Override
protected JsonArray<String> getLocalVariables(ParseResult<State> stateParseResult) {
return JsonCollections.createArray();
}
@Override
protected PrefixIndex<TemplateProposal> getTemplatesIndex() {
return new AbstractTrie<TemplateProposal>();
}
@Override
protected boolean checkIsThisPrefix(String prefix) {
return "zis.".equals(prefix);
}
}
private PathUtil path;
private MockAutocompleterEnvironment helper;
private CodeGraphAutocompleter autocompleter;
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
@Override
public void gwtSetUp() throws Exception {
super.gwtSetUp();
path = new PathUtil("/test.none");
helper = new MockAutocompleterEnvironment();
SkipListStringBag localPrefixIndexStorage = new SkipListStringBag();
LimitedContextFilePrefixIndex contextFilePrefixIndex = new LimitedContextFilePrefixIndex(
10, localPrefixIndexStorage);
autocompleter = new CodeGraphAutocompleter(SyntaxType.JS, new MockProposalBuilder(),
helper.cubeClient, contextFilePrefixIndex, new ExplicitAutocompleter());
helper.specificAutocompleter = autocompleter;
}
public void testFullFunctionCompletion() {
helper.setup(path, "get", 0, 3, false);
autocompleter.findAutocompletions(helper.editor.getSelection(), CTRL_SPACE);
AutocompleteProposal functionProposal = new CodeGraphProposal("getFoo",
path, true);
AutocompleteResult commonResult = autocompleter.computeAutocompletionResult(
new ProposalWithContext(SyntaxType.NONE, functionProposal, new Context("get")));
assertTrue("result type", commonResult instanceof DefaultAutocompleteResult);
DefaultAutocompleteResult result = (DefaultAutocompleteResult) commonResult;
assertEquals("jump length", 7, result.getJumpLength());
assertEquals("autocompletion text", "getFoo()", result.getAutocompletionText());
}
/*
* TODO: Write test that tests proposals update when updater
* fires notification
*/
public void testFullPropertyCompletion() {
helper.setup(path, "g", 0, 1, false);
autocompleter.findAutocompletions(helper.editor.getSelection(), CTRL_SPACE);
AutocompleteProposal propertyProposal = new CodeGraphProposal("gender",
path, false);
AutocompleteResult commonResult = autocompleter.computeAutocompletionResult(
new ProposalWithContext(SyntaxType.NONE, propertyProposal, new Context("get")));
assertTrue("result type", commonResult instanceof DefaultAutocompleteResult);
DefaultAutocompleteResult result = (DefaultAutocompleteResult) commonResult;
assertEquals("jump length", 6, result.getJumpLength());
assertEquals("autocompletion text", "gender", result.getAutocompletionText());
}
public void testTemplateProcessing() {
helper.setup(path, "", 0, 0, false);
autocompleter.findAutocompletions(helper.editor.getSelection(), CTRL_SPACE);
AutocompleteProposal proposal = new TemplateProposal("simple", "simple (%c) <%i%n>");
AutocompleteResult commonResult = autocompleter.computeAutocompletionResult(
new ProposalWithContext(SyntaxType.NONE, proposal, new Context("")));
assertTrue("result type", commonResult instanceof DefaultAutocompleteResult);
DefaultAutocompleteResult result = (DefaultAutocompleteResult) commonResult;
assertEquals("autocompletion text", "simple () <\n \n>", result.getAutocompletionText());
assertEquals("jump length", 8, result.getJumpLength());
assertEquals("backspace count", 0, result.getBackspaceCount());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/codegraph/ProposalBuilderTest.java | javatests/com/google/collide/client/code/autocomplete/codegraph/ProposalBuilderTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.codegraph;
import static com.google.collide.codemirror2.TokenType.NULL;
import static com.google.collide.codemirror2.TokenType.VARIABLE;
import static com.google.collide.codemirror2.TokenType.WHITESPACE;
import com.google.collide.client.code.autocomplete.TestUtils;
import com.google.collide.client.documentparser.ParseResult;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.collide.codemirror2.State;
import com.google.collide.codemirror2.Token;
import com.google.collide.codemirror2.TokenType;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import javax.annotation.Nullable;
/**
* Test cases for {@link ProposalBuilder}.
*
*/
public class ProposalBuilderTest extends SynchronousTestCase {
private static final RegExp PARSER = RegExp.compile("^(([A-Za-z]+)|([(+).])|(\\s+))");
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
public void testTriggeringString() {
checkContext("empty", "", null, "");
checkContext("simple", "foo", null, "foo");
checkContext("spaceless expression", "bar", null, "foo+bar");
checkContext("expression", "bar", null, " + bar");
checkContext("period, space, id", "get", null, ". get");
checkContext("property", "get", null, "foo.get");
checkContext("empty property", "", "foo.", "foo.");
checkContext("empty cascade-property", "", "foo.foo.", "foo.foo.");
}
private void checkContext(String message, String triggeringString, @Nullable String prevContext,
String text) {
ProposalBuilder<State> proposalBuilder = new CodeGraphAutocompleterTest.MockProposalBuilder();
CompletionContext<State> context = proposalBuilder.buildContext(parse(text));
assertEquals(
message + ": triggering string", triggeringString, context.getTriggeringString());
if (prevContext != null) {
assertEquals(
message + ": previous context", prevContext, context.getPreviousContext());
}
}
private ParseUtils.ExtendedParseResult<State> parse(String text) {
JsonArray<Token> tokens = JsonCollections.createArray();
while (text.length() > 0) {
MatchResult result = PARSER.exec(text);
if (result == null) {
throw new IllegalArgumentException("Can't parse: " + text);
}
String value;
TokenType type;
if (result.getGroup(2) != null) {
value = result.getGroup(2);
type = VARIABLE;
} else if (result.getGroup(3) != null) {
value = result.getGroup(3);
type = NULL;
} else if (result.getGroup(4) != null) {
value = result.getGroup(4);
type = WHITESPACE;
} else {
throw new IllegalArgumentException("Can't parse: " + result.getGroup(1));
}
tokens.add(new Token("test", type, value));
text = text.substring(value.length());
}
ParseResult<State> parseResult = new ParseResult<State>(tokens, TestUtils.createMockState());
return new ParseUtils.ExtendedParseResult<State>(parseResult, ParseUtils.Context.IN_CODE);
}
public void testPreviousContextTrimming() {
String text = " goog.le ";
checkContext("before property", "", "goog.", text.substring(0, 8));
checkContext("after property", "le", "goog.", text.substring(0, 10));
checkContext("after property and space", "", "", text.substring(0, 11));
}
public void testStripFunctionCallBraces() {
checkContext("brace", "", "", "getFoo()");
checkContext("braces and period", "", "getFoo.", "getFoo().");
checkContext("id in braces and period", "", "getFoo.", "getFoo(bar).");
checkContext("braces, period, id", "getBar", "getFoo.", "getFoo().getBar");
checkContext("new in braces, period", "", ".", "(new Foo()).");
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/codegraph/JsIndexUpdaterTest.java | javatests/com/google/collide/client/code/autocomplete/codegraph/JsIndexUpdaterTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.codegraph;
import com.google.collide.client.code.autocomplete.codegraph.js.JsCodeScope;
import com.google.collide.client.code.autocomplete.codegraph.js.JsIndexUpdater;
import com.google.collide.client.code.autocomplete.integration.TaggableLineUtil;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.collide.codemirror2.SyntaxType;
import com.google.collide.codemirror2.Token;
import com.google.collide.codemirror2.TokenType;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.TaggableLine;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.util.JsonCollections;
/**
* Test cases for {@link JsIndexUpdater}
*
*/
public class JsIndexUpdaterTest extends SynchronousTestCase {
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
public void testSimpleCases() {
String mode = SyntaxType.JS.getName();
String text = ""
+ "function a(b, c) {\n"
+ " d.prototype = function() {\n"
+ " }\n"
+ "}\n"
+ "var e = {\n"
+ " f : function ( ) {\n"
+ " callMyFunctionWithCallback(function(/* Knock-knock! */) {\n";
Document document = Document.createFromString(text);
Line line = document.getFirstLine();
TaggableLine previousLine;
JsonArray<Token> tokens1 = JsonCollections.createArray();
tokens1.add(new Token(mode, TokenType.KEYWORD, "function"));
tokens1.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens1.add(new Token(mode, TokenType.VARIABLE, "a"));
tokens1.add(new Token(mode, TokenType.NULL, "("));
tokens1.add(new Token(mode, TokenType.VARIABLE, "b"));
tokens1.add(new Token(mode, TokenType.NULL, ","));
tokens1.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens1.add(new Token(mode, TokenType.VARIABLE, "c"));
tokens1.add(new Token(mode, TokenType.NULL, ")"));
tokens1.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens1.add(new Token(mode, TokenType.NULL, "{"));
tokens1.add(new Token(mode, TokenType.NEWLINE, "\n"));
JsonArray<Token> tokens2 = JsonCollections.createArray();
tokens2.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens2.add(new Token(mode, TokenType.VARIABLE, "d"));
tokens2.add(new Token(mode, TokenType.NULL, "."));
tokens2.add(new Token(mode, TokenType.VARIABLE, "prototype"));
tokens2.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens2.add(new Token(mode, TokenType.NULL, "="));
tokens2.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens2.add(new Token(mode, TokenType.KEYWORD, "function"));
tokens2.add(new Token(mode, TokenType.NULL, "("));
tokens2.add(new Token(mode, TokenType.NULL, ")"));
tokens2.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens2.add(new Token(mode, TokenType.NULL, "{"));
tokens2.add(new Token(mode, TokenType.NEWLINE, "\n"));
JsonArray<Token> tokens3 = JsonCollections.createArray();
tokens3.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens3.add(new Token(mode, TokenType.NULL, "}"));
tokens3.add(new Token(mode, TokenType.NEWLINE, "\n"));
JsonArray<Token> tokens4 = JsonCollections.createArray();
tokens4.add(new Token(mode, TokenType.NULL, "}"));
tokens4.add(new Token(mode, TokenType.NEWLINE, "\n"));
JsonArray<Token> tokens5 = JsonCollections.createArray();
tokens5.add(new Token(mode, TokenType.KEYWORD, "var"));
tokens5.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens5.add(new Token(mode, TokenType.DEF, "e"));
tokens5.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens5.add(new Token(mode, TokenType.NULL, "="));
tokens5.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens5.add(new Token(mode, TokenType.NULL, "{"));
tokens5.add(new Token(mode, TokenType.NEWLINE, "\n"));
JsonArray<Token> tokens6 = JsonCollections.createArray();
tokens6.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens6.add(new Token(mode, TokenType.PROPERTY, "f"));
tokens6.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens6.add(new Token(mode, TokenType.NULL, ":"));
tokens6.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens6.add(new Token(mode, TokenType.KEYWORD, "function"));
tokens6.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens6.add(new Token(mode, TokenType.NULL, "("));
tokens6.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens6.add(new Token(mode, TokenType.NULL, ")"));
tokens6.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens6.add(new Token(mode, TokenType.NULL, "{"));
tokens6.add(new Token(mode, TokenType.NEWLINE, "\n"));
JsonArray<Token> tokens7 = JsonCollections.createArray();
tokens7.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens7.add(new Token(mode, TokenType.VARIABLE, "callMyFunctionWithCallback"));
tokens7.add(new Token(mode, TokenType.NULL, "("));
tokens7.add(new Token(mode, TokenType.KEYWORD, "function"));
tokens7.add(new Token(mode, TokenType.NULL, "("));
tokens7.add(new Token(mode, TokenType.COMMENT, "/* Knock-knock! */"));
tokens7.add(new Token(mode, TokenType.NULL, ")"));
tokens7.add(new Token(mode, TokenType.WHITESPACE, " "));
tokens7.add(new Token(mode, TokenType.NULL, "{"));
tokens7.add(new Token(mode, TokenType.NEWLINE, "\n"));
JsIndexUpdater indexUpdater = new JsIndexUpdater();
indexUpdater.onBeforeParse();
previousLine = TaggableLineUtil.getPreviousLine(line);
indexUpdater.onParseLine(previousLine, line, tokens1);
JsCodeScope aScope = line.getTag(JsIndexUpdater.TAG_SCOPE);
assertNotNull(aScope);
assertEquals("a", aScope.getName());
line = line.getNextLine();
previousLine = TaggableLineUtil.getPreviousLine(line);
indexUpdater.onParseLine(previousLine, line, tokens2);
JsCodeScope dProtoScope = line.getTag(JsIndexUpdater.TAG_SCOPE);
assertNotNull(dProtoScope);
assertEquals("d.prototype", dProtoScope.getName());
assertTrue(dProtoScope.getParent() == aScope);
assertEquals("a-d-prototype", JsCodeScope.buildPrefix(dProtoScope).join("-"));
line = line.getNextLine();
previousLine = TaggableLineUtil.getPreviousLine(line);
indexUpdater.onParseLine(previousLine, line, tokens3);
assertTrue(line.getTag(JsIndexUpdater.TAG_SCOPE) == aScope);
line = line.getNextLine();
previousLine = TaggableLineUtil.getPreviousLine(line);
indexUpdater.onParseLine(previousLine, line, tokens4);
assertFalse(line.getTag(JsIndexUpdater.TAG_SCOPE) == aScope);
line = line.getNextLine();
previousLine = TaggableLineUtil.getPreviousLine(line);
indexUpdater.onParseLine(previousLine, line, tokens5);
JsCodeScope eScope = line.getTag(JsIndexUpdater.TAG_SCOPE);
assertNotNull(eScope);
assertEquals("e", eScope.getName());
assertFalse(eScope.getParent() == aScope);
line = line.getNextLine();
previousLine = TaggableLineUtil.getPreviousLine(line);
indexUpdater.onParseLine(previousLine, line, tokens6);
JsCodeScope fScope = line.getTag(JsIndexUpdater.TAG_SCOPE);
assertNotNull(fScope);
assertEquals("f", fScope.getName());
assertTrue(fScope.getParent() == eScope);
line = line.getNextLine();
previousLine = TaggableLineUtil.getPreviousLine(line);
indexUpdater.onParseLine(previousLine, line, tokens7);
JsCodeScope namelessScope = line.getTag(JsIndexUpdater.TAG_SCOPE);
assertNotNull(namelessScope);
assertNull(namelessScope.getName());
assertTrue(namelessScope.getParent() == fScope);
indexUpdater.onAfterParse();
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/codegraph/js/JsProposalBuilderTest.java | javatests/com/google/collide/client/code/autocomplete/codegraph/js/JsProposalBuilderTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.codegraph.js;
import com.google.collide.client.code.autocomplete.codegraph.CompletionContext;
import com.google.collide.client.code.autocomplete.codegraph.CompletionType;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.collide.codemirror2.JsState;
import com.google.collide.json.shared.JsonStringSet;
import com.google.collide.shared.util.JsonCollections;
// TODO: We need to add some CUBE+client tests for typical cases.
/**
* Test cases for JS specific things performed by {@link JsProposalBuilder}.
*/
public class JsProposalBuilderTest extends SynchronousTestCase {
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
public void testGlobalShortcuts() {
JsProposalBuilder jsProposalBuilder = new JsProposalBuilder();
CompletionContext<JsState> context = new CompletionContext<JsState>(
"", "con", false, CompletionType.GLOBAL, null, 0);
JsonStringSet prefixes = JsonCollections.createStringSet();
prefixes.add("");
prefixes.add("Tofu.");
jsProposalBuilder.addShortcutsTo(context, prefixes);
assertEquals(JsonCollections.createStringSet("", "Tofu.", "window."), prefixes);
}
public void testPropertyShortcuts() {
JsProposalBuilder jsProposalBuilder = new JsProposalBuilder();
CompletionContext<JsState> context = new CompletionContext<JsState>(
"console.", "deb", false, CompletionType.PROPERTY, null, 0);
JsonStringSet prefixes = JsonCollections.createStringSet();
prefixes.add("console.");
prefixes.add("Tofu.console.");
jsProposalBuilder.addShortcutsTo(context, prefixes);
assertEquals(JsonCollections.createStringSet("console.", "Tofu.console.", "window.console."),
prefixes);
}
public void testThisShortcuts() {
JsProposalBuilder jsProposalBuilder = new JsProposalBuilder();
CompletionContext<JsState> context = new CompletionContext<JsState>(
"this.console.", "deb", true, CompletionType.PROPERTY, null, 0);
JsonStringSet prefixes = JsonCollections.createStringSet();
prefixes.add("Tofu.console.");
jsProposalBuilder.addShortcutsTo(context, prefixes);
assertEquals(JsonCollections.createStringSet("Tofu.console."), prefixes);
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/css/CssValuesTest.java | javatests/com/google/collide/client/code/autocomplete/css/CssValuesTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.css;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import org.junit.Before;
/**
*
*/
public class CssValuesTest extends SynchronousTestCase {
CssPartialParser cssPartialParser;
@Override
public String getModuleName() {
return "com.google.cofllide.client.TestCode";
}
@Override
@Before
public void gwtSetUp() {
cssPartialParser = CssPartialParser.getInstance();
}
public void testAzimuth() {
JsArray<JavaScriptObject> valuesForAllSlots = cssPartialParser.getPropertyValues("azimuth");
assertEquals(2, valuesForAllSlots.length());
}
public void testBackgroundAttachment() {
JsArray<JavaScriptObject> valuesForAllSlots =
cssPartialParser.getPropertyValues("background-attachment");
assertEquals(1, valuesForAllSlots.length());
}
public void testBorderLeft() {
JsArray<JavaScriptObject> valuesForAllSlots = cssPartialParser.getPropertyValues("border-left");
assertEquals(3, valuesForAllSlots.length());
}
public void testBorderTopStyle() {
JsArray<JavaScriptObject> valuesForAllSlots =
cssPartialParser.getPropertyValues("border-top-style");
assertEquals(1, valuesForAllSlots.length());
}
public void testBorderWidth() {
JsArray<JavaScriptObject> valuesForAllSlots =
cssPartialParser.getPropertyValues("border-width");
assertEquals(2, valuesForAllSlots.length());
}
public void testBottom() {
JsArray<JavaScriptObject> valuesForAllSlots = cssPartialParser.getPropertyValues("bottom");
assertEquals(1, valuesForAllSlots.length());
}
public void testColor() {
JsArray<JavaScriptObject> valuesForAllSlots = cssPartialParser.getPropertyValues("color");
assertEquals(1, valuesForAllSlots.length());
}
public void testWidth() {
JsArray<JavaScriptObject> valuesForAllSlots = cssPartialParser.getPropertyValues("width");
assertEquals(1, valuesForAllSlots.length());
}
public void testZIndex() {
JsArray<JavaScriptObject> valuesForAllSlots = cssPartialParser.getPropertyValues("z-index");
assertEquals(1, valuesForAllSlots.length());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/css/CssAutocompleteTest.java | javatests/com/google/collide/client/code/autocomplete/css/CssAutocompleteTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.css;
import static com.google.collide.client.code.autocomplete.TestUtils.CTRL_SPACE;
import static com.google.collide.client.code.autocomplete.css.CssTrie.findAndFilterAutocompletions;
import com.google.collide.client.code.autocomplete.AbstractTrie;
import com.google.collide.client.code.autocomplete.AutocompleteProposal;
import com.google.collide.client.code.autocomplete.AutocompleteProposals;
import com.google.collide.client.code.autocomplete.AutocompleteProposals.ProposalWithContext;
import com.google.collide.client.code.autocomplete.AutocompleteResult;
import com.google.collide.client.code.autocomplete.DefaultAutocompleteResult;
import com.google.collide.client.code.autocomplete.MockAutocompleterEnvironment;
import com.google.collide.client.code.autocomplete.TestUtils;
import com.google.collide.client.editor.selection.SelectionModel;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.collide.client.util.PathUtil;
import com.google.collide.json.client.JsoArray;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.base.Joiner;
/**
* Tests for css autocompletion.
*
*/
public class CssAutocompleteTest extends SynchronousTestCase {
private CssAutocompleter cssAutocompleter;
private MockAutocompleterEnvironment helper;
@Override
public String getModuleName() {
return "com.google.cofllide.client.TestCode";
}
@Override
public void gwtSetUp() throws Exception {
super.gwtSetUp();
cssAutocompleter = CssAutocompleter.create();
helper = new MockAutocompleterEnvironment();
}
public void testFindAndFilterAutocompletions() {
AbstractTrie<AutocompleteProposal> cssTrie = CssTrie.createTrie();
JsonArray<String> completedProps = JsonCollections.createArray();
JsonArray<AutocompleteProposal> proposals;
proposals = findAndFilterAutocompletions(cssTrie, "clea", completedProps);
assertEquals(1, proposals.size());
assertEquals("clear", proposals.get(0).getName());
proposals = findAndFilterAutocompletions(cssTrie, "clear", completedProps);
assertEquals(1, proposals.size());
assertEquals("clear", proposals.get(0).getName());
proposals = findAndFilterAutocompletions(cssTrie, "hiybbprqag", completedProps);
assertEquals(0, proposals.size());
proposals = findAndFilterAutocompletions(cssTrie, "", completedProps);
assertEquals(115, proposals.size());
completedProps.add("clear");
proposals = findAndFilterAutocompletions(cssTrie, "", completedProps);
assertEquals(114, proposals.size());
}
/**
* Tests getting the context.
*/
public void testAttributeNameFullAutocompletion() {
String text = Joiner.on("").join(new String[]{
".something {\n",
"cur\n",
"color: black;\n",
"fake: ;\n",
"}\n"
});
helper.setup(new PathUtil("test.css"), text, 1, 3, false);
SelectionModel selection = helper.editor.getSelection();
AutocompleteProposals completions = cssAutocompleter.findAutocompletions(selection, CTRL_SPACE);
assertEquals(1, completions.size());
AutocompleteResult commonResult = cssAutocompleter.computeAutocompletionResult(
completions.select(0));
assertTrue("result type", commonResult instanceof DefaultAutocompleteResult);
DefaultAutocompleteResult result = (DefaultAutocompleteResult) commonResult;
assertEquals(8, result.getJumpLength());
assertEquals("cursor: ;", result.getAutocompletionText());
CssCompletionQuery query = cssAutocompleter.updateOrCreateQuery(
null, selection.getCursorPosition());
JsoArray<String> completedProperties = query.getCompletedProperties();
assertEquals(2, completedProperties.size());
assertEquals("color", completedProperties.get(0));
assertEquals("fake", completedProperties.get(1));
}
/**
* Tests getting the context.
*/
public void testAttributeValueFullAutocompletion() {
String text = Joiner.on("").join(new String[]{
".something {\n",
"azimuth: \n",
});
helper.setup(new PathUtil("/some.css"), text, 1, 9, false);
AutocompleteProposals completions = cssAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
assertEquals(14, completions.size());
ProposalWithContext leftSideProposal = TestUtils.selectProposalByName(completions, "left-side");
assertNotNull(leftSideProposal);
AutocompleteResult commonResult = cssAutocompleter.computeAutocompletionResult(
leftSideProposal);
assertTrue("result type", commonResult instanceof DefaultAutocompleteResult);
DefaultAutocompleteResult result = (DefaultAutocompleteResult) commonResult;
assertEquals(9, result.getJumpLength());
}
/**
* Tests filtering out properties that appear after.
*/
public void testFilterPropertiesAfter() {
CssCompletionQuery cssCompletionQuery =
new CssCompletionQuery("back", "color: blue;\nfake: ;\nbackground-color: blue;");
JsonArray<AutocompleteProposal> proposals =
findAndFilterAutocompletions(CssTrie.createTrie(), cssCompletionQuery.getTriggeringString(),
cssCompletionQuery.getCompletedProperties());
// Notably, the list does not contain background-color.
assertEquals(5, proposals.size());
assertEquals("background", proposals.get(0).getName());
assertEquals("background-attachment", proposals.get(1).getName());
assertEquals("background-image", proposals.get(2).getName());
assertEquals("background-position", proposals.get(3).getName());
assertEquals("background-repeat", proposals.get(4).getName());
}
/**
* Tests filtering out properties that appear after.
*/
public void testFilterExistingValuesAfter() {
CssCompletionQuery cssCompletionQuery = new CssCompletionQuery(
"background: ", "black;\ncolor: blue;\nfake: ;\nbackground-color: blue;");
JsoArray<AutocompleteProposal> proposals =
CssPartialParser.getInstance().getAutocompletions(cssCompletionQuery.getProperty(),
cssCompletionQuery.getValuesBefore(), cssCompletionQuery.getTriggeringString(),
cssCompletionQuery.getValuesAfter());
// Notably, the list does not contain colors.
assertEquals(2, proposals.size());
assertEquals("transparent", proposals.get(0).getName());
assertEquals("inherit", proposals.get(1).getName());
}
/**
* Tests filtering out properties that appear before.
*/
public void testFilterExistingValuesBefore() {
CssCompletionQuery cssCompletionQuery = new CssCompletionQuery(
"background: black ", "\ncolor: blue;\nfake: ;\nbackground-color: blue;");
JsoArray<AutocompleteProposal> proposals =
CssPartialParser.getInstance().getAutocompletions(cssCompletionQuery.getProperty(),
cssCompletionQuery.getValuesBefore(), cssCompletionQuery.getTriggeringString(),
cssCompletionQuery.getValuesAfter());
// Notably, the list does not contain colors.
assertEquals(3, proposals.size());
assertEquals("<uri>", proposals.get(0).getName());
assertEquals("none", proposals.get(1).getName());
assertEquals("inherit", proposals.get(2).getName());
}
/**
* Tests that for some properties values can be repeated, so they are proposed
* again.
*/
public void testRepeatingProperties() {
CssCompletionQuery cssCompletionQuery = new CssCompletionQuery(
"padding: 19px ", "\ncolor: blue;\nfake: ;\nbackground-color: blue;");
JsoArray<AutocompleteProposal> proposals =
CssPartialParser.getInstance().getAutocompletions(cssCompletionQuery.getProperty(),
cssCompletionQuery.getValuesBefore(), cssCompletionQuery.getTriggeringString(),
cssCompletionQuery.getValuesAfter());
// Notably, the list does not contain colors.
assertEquals(10, proposals.size());
assertEquals("<number>em", proposals.get(0).getName());
assertEquals("<number>ex", proposals.get(1).getName());
assertEquals("<number>in", proposals.get(2).getName());
assertEquals("<number>cm", proposals.get(3).getName());
assertEquals("<number>mm", proposals.get(4).getName());
assertEquals("<number>pt", proposals.get(5).getName());
assertEquals("<number>pc", proposals.get(6).getName());
assertEquals("<number>px", proposals.get(7).getName());
assertEquals("<number>%", proposals.get(8).getName());
assertEquals("inherit", proposals.get(9).getName());
}
/**
* Tests that number proposals come up first for the property 'border'.
*/
public void testBorder() {
CssCompletionQuery cssCompletionQuery =
new CssCompletionQuery("border: ", "\ncolor: blue;\nfake: ;\nbackground-color: blue;");
JsoArray<AutocompleteProposal> proposals =
CssPartialParser.getInstance().getAutocompletions(cssCompletionQuery.getProperty(),
cssCompletionQuery.getValuesBefore(), cssCompletionQuery.getTriggeringString(),
cssCompletionQuery.getValuesAfter());
// Notably, number proposals are first.
assertEquals(43, proposals.size());
assertEquals("<number>em", proposals.get(0).getName());
}
/**
* Tests filtering out properties that appear after 'border'.
*/
public void testBorderWithExistingValue() {
CssCompletionQuery cssCompletionQuery =
new CssCompletionQuery("border: 1px ", "color: blue;\nfake: ;\nbackground-color: blue;");
JsoArray<AutocompleteProposal> proposals =
CssPartialParser.getInstance().getAutocompletions(cssCompletionQuery.getProperty(),
cssCompletionQuery.getValuesBefore(), cssCompletionQuery.getTriggeringString(),
cssCompletionQuery.getValuesAfter());
// Notably, the list does not contain background-color.
assertEquals(15, proposals.size());
}
public void testQueryType() {
CssCompletionQuery query = new CssCompletionQuery("clea", "");
assertEquals(CompletionType.PROPERTY, query.getCompletionType());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/css/CssSpecialValuesTest.java | javatests/com/google/collide/client/code/autocomplete/css/CssSpecialValuesTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.css;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.gwt.core.client.JsArrayString;
public class CssSpecialValuesTest extends SynchronousTestCase {
CssPartialParser cssPartialParser;
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
@Override
public void gwtSetUp() throws Exception {
super.gwtSetUp();
cssPartialParser = CssPartialParser.getInstance();
}
public void testAngle() {
JsArrayString proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("19deg", "<angle>");
assertTrue(proposals.length() > 0);
proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("222rad", "<angle>");
assertTrue(proposals.length() > 0);
proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("22grad", "<angle>");
assertTrue(proposals.length() > 0);
proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("-22grad", "<angle>");
assertTrue(proposals.length() > 0);
proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("22.2grad", "<angle>");
assertTrue(proposals.length() > 0);
proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("-22.2grad", "<angle>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("22foo", "<angle>");
assertEquals(0, proposals.length());
proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("-22foo", "<angle>");
assertEquals(0, proposals.length());
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("", "<angle>");
assertEquals(0, proposals.length());
}
public void testColor() {
JsArrayString proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("olive", "<color>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("white", "<color>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("#fa0", "<color>");
assertTrue(proposals.length() > 0);
proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("#f9a711", "<color>");
assertTrue(proposals.length() > 0);
proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("rgb(10,10,10)", "<color>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals(
"rgb(10, 10, 10)", "<color>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals(
"rgb(10%,10%,10%)", "<color>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals(
"rgb(10%, 10%, 10%)", "<color>");
assertTrue(proposals.length() > 0);
proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("blueishgreen", "<color>");
assertEquals(0, proposals.length());
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("rgb()", "<color>");
assertEquals(0, proposals.length());
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("#f", "<color>");
assertEquals(0, proposals.length());
}
public void testCounter() {
JsArrayString proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals(
"counter(par-num, upper-roman)", "<counter>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals(
"counter(par-num)", "<counter>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals(
"c(par-num, upper-roman)", "<counter>");
assertEquals(0, proposals.length());
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("foo", "<counter>");
assertEquals(0, proposals.length());
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("", "<counter>");
assertEquals(0, proposals.length());
}
public void testFrequency() {
JsArrayString proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("100kHz", "<frequency>");
assertTrue(proposals.length() > 0);
// Note: this seems wrong, but is permissible as per the CSS2 spec.
proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("-10Hz", "<frequency>");
assertTrue(proposals.length() > 0);
proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("100", "<frequency>");
assertEquals(0, proposals.length());
proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("foo", "<frequency>");
assertEquals(0, proposals.length());
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("", "<frequency>");
assertEquals(0, proposals.length());
}
public void testInteger() {
JsArrayString proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("19", "<integer>");
assertTrue(proposals.length() > 0);
proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("-2200", "<integer>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("+22", "<integer>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("vvv", "<integer>");
assertEquals(0, proposals.length());
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("22.", "<integer>");
assertEquals(0, proposals.length());
proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("22.2grad", "<integer>");
assertEquals(0, proposals.length());
}
public void testNumber() {
JsArrayString proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("19", "<number>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("22.2", "<number>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("-22", "<number>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("+22", "<number>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("vvv", "<number>");
assertEquals(0, proposals.length());
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("22.", "<number>");
assertEquals(0, proposals.length());
proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("22.2grad", "<number>");
assertEquals(0, proposals.length());
}
public void testPercentage() {
JsArrayString proposals =
cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("10em", "<length>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("0mm", "<length>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("10px", "<length>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("foo", "<length>");
assertEquals(0, proposals.length());
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("", "<length>");
assertEquals(0, proposals.length());
}
public void testShape() {
JsArrayString proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals(
"rect(10em, 10em, 10em, 10em)", "<shape>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals(
"rect(10px, 10px , 10px, 10px)", "<shape>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals(
"r(10em, 10em, 10em, 10em)", "<shape>");
assertEquals(0, proposals.length());
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("foo", "<shape>");
assertEquals(0, proposals.length());
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("", "<shape>");
assertEquals(0, proposals.length());
}
public void testUri() {
JsArrayString proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals(
"https://mail.google.com", "<uri>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals(
"http://www.google.com", "<uri>");
assertTrue(proposals.length() > 0);
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("wwww", "<uri>");
assertEquals(0, proposals.length());
proposals = cssPartialParser.checkIfSpecialValueAndGetSpecialValueProposals("", "<uri>");
assertEquals(0, proposals.length());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/html/HtmlAutocompleteTest.java | javatests/com/google/collide/client/code/autocomplete/html/HtmlAutocompleteTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.html;
import static com.google.collide.client.code.autocomplete.TestUtils.CTRL_SPACE;
import com.google.collide.client.code.autocomplete.AutocompleteProposals;
import com.google.collide.client.code.autocomplete.AutocompleteProposals.ProposalWithContext;
import com.google.collide.client.code.autocomplete.AutocompleteResult;
import com.google.collide.client.code.autocomplete.DefaultAutocompleteResult;
import com.google.collide.client.code.autocomplete.MockAutocompleterEnvironment;
import com.google.collide.client.code.autocomplete.TestUtils;
import com.google.collide.client.code.autocomplete.integration.DocumentParserListenerAdapter;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.collide.client.testutil.TestSchedulerImpl;
import com.google.collide.client.util.IncrementalScheduler;
import com.google.collide.client.util.PathUtil;
import com.google.collide.client.util.collections.SimpleStringBag;
import com.google.collide.codemirror2.CodeMirror2;
import com.google.collide.codemirror2.State;
import com.google.collide.codemirror2.Stream;
import com.google.collide.codemirror2.SyntaxType;
import com.google.collide.codemirror2.Token;
import com.google.collide.codemirror2.TokenType;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.Pair;
import com.google.collide.shared.document.Document;
import com.google.collide.shared.document.Line;
import com.google.collide.shared.document.anchor.Anchor;
import com.google.collide.shared.document.anchor.AnchorManager;
import com.google.collide.shared.util.JsonCollections;
import com.google.common.base.Preconditions;
/**
* Tests for html autocompletion.
*/
public class HtmlAutocompleteTest extends SynchronousTestCase {
private MockAutocompleterEnvironment helper;
private PathUtil path;
private JsonStringMap<JsonArray<Token>> parsedLines;
private JsonArray<Token> lineTokens;
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
@Override
public void gwtSetUp() throws Exception {
super.gwtSetUp();
helper = new MockAutocompleterEnvironment();
path = new PathUtil("/test.html");
lineTokens = JsonCollections.createArray();
parsedLines = JsonCollections.createMap();
helper.specificParser = new TestUtils.MockParser(SyntaxType.HTML) {
@Override
public void parseNext(Stream stream, State parserState, JsonArray<Token> tokens) {
Preconditions.checkState(stream instanceof TestUtils.MockStream);
JsonArray<Token> lineTokens = parsedLines.get(((TestUtils.MockStream) stream).getText());
if (lineTokens != null) {
tokens.addAll(lineTokens);
}
}
};
}
private AutocompleteProposals findAutocompletions() {
prepareAutocompleter();
return helper.autocompleter.htmlAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
}
private void parseOneLine() {
Runnable runnable = new Runnable() {
@Override
public void run() {
JsonArray<IncrementalScheduler.Task> requests = helper.parseScheduler.requests;
if (!requests.peek().run(1)) {
requests.pop();
}
}
};
TestSchedulerImpl.AngryScheduler scheduler = new TestSchedulerImpl.AngryScheduler() {
@Override
public void scheduleDeferred(ScheduledCommand scheduledCommand) {
scheduledCommand.execute();
}
};
TestSchedulerImpl.runWithSpecificScheduler(runnable, scheduler);
}
private void prepareAutocompleter() {
String text = tokensToText(lineTokens);
parsedLines.put(text, lineTokens);
helper.setup(path, text, 0, text.length(), false);
helper.parser.getListenerRegistrar().add(new DocumentParserListenerAdapter(
helper.autocompleter, helper.editor));
helper.parser.begin();
parseOneLine();
}
private String tokensToText(JsonArray<Token> tokens) {
StringBuilder builder = new StringBuilder();
for (Token token : tokens.asIterable()) {
builder.append(token.getValue());
}
return builder.toString();
}
/**
* Tests attributes proposals.
*/
public void testHtmlAttributes() {
HtmlTagsAndAttributes htmlAttributes = HtmlTagsAndAttributes.getInstance();
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<html"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.WHITESPACE, " "));
AutocompleteProposals proposals = findAutocompletions();
assertEquals(htmlAttributes.searchAttributes("html", new SimpleStringBag(), "").size(),
proposals.size());
assertEquals("accesskey", proposals.get(0).getName());
}
/**
* Tests that proposal list is updated when parsing of tag is finished.
*/
public void testUpdateOnTagFinish() {
String sampleAttribute = "accesskey";
HtmlTagsAndAttributes htmlAttributes = HtmlTagsAndAttributes.getInstance();
SimpleStringBag excluded = new SimpleStringBag();
assertEquals(1, htmlAttributes.searchAttributes("html", excluded, sampleAttribute).size());
excluded.add(sampleAttribute);
JsonArray<Token> tokens1 = JsonCollections.createArray();
tokens1.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<html"));
tokens1.add(new Token(CodeMirror2.HTML, TokenType.WHITESPACE, " "));
String line1 = tokensToText(tokens1);
parsedLines.put(line1, tokens1);
JsonArray<Token> tokens2 = JsonCollections.createArray();
tokens2.add(new Token(CodeMirror2.HTML, TokenType.ATTRIBUTE, sampleAttribute));
tokens2.add(new Token(CodeMirror2.HTML, TokenType.TAG, ">"));
String line2 = tokensToText(tokens2);
parsedLines.put(line2, tokens2);
String text = line1 + "\n" + line2 + "\n";
helper.setup(path, text, 0, line1.length(), false);
helper.parser.getListenerRegistrar().add(new DocumentParserListenerAdapter(
helper.autocompleter, helper.editor));
helper.parser.begin();
parseOneLine();
helper.autocompleter.requestAutocomplete();
// "...please wait..."
assertEquals(1, helper.popup.proposals.size());
parseOneLine();
assertEquals(htmlAttributes.searchAttributes("html", excluded, "").size(),
helper.popup.proposals.size());
}
/**
* Tests that {@link HtmlAutocompleter#getModeForColumn} gets the mode from
* the anchor set prior to the given column.
*/
public void testGetModeForColumn() {
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<html"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.WHITESPACE, " "));
prepareAutocompleter();
Document document = helper.editor.getDocument();
AnchorManager anchorManager = document.getAnchorManager();
Line line = document.getFirstLine();
HtmlAutocompleter htmlAutocompleter = helper.autocompleter.htmlAutocompleter;
// Delete the anchor that was set by prepareAutocompleter().
JsonArray<Anchor> anchors =
AnchorManager.getAnchorsByTypeOrNull(line, HtmlAutocompleter.MODE_ANCHOR_TYPE);
assertEquals(0, anchors.size());
assertEquals(CodeMirror2.HTML, htmlAutocompleter.getModeForColumn(line, 0));
assertEquals(CodeMirror2.HTML, htmlAutocompleter.getModeForColumn(line, 1));
assertEquals(CodeMirror2.HTML, htmlAutocompleter.getModeForColumn(line, 2));
assertEquals(CodeMirror2.HTML, htmlAutocompleter.getModeForColumn(line, 3));
Anchor anchor = anchorManager.createAnchor(HtmlAutocompleter.MODE_ANCHOR_TYPE, line,
AnchorManager.IGNORE_LINE_NUMBER, 2);
anchor.setValue("m1");
assertEquals(CodeMirror2.HTML, htmlAutocompleter.getModeForColumn(line, 0));
assertEquals(CodeMirror2.HTML, htmlAutocompleter.getModeForColumn(line, 1));
assertEquals(CodeMirror2.HTML, htmlAutocompleter.getModeForColumn(line, 2));
assertEquals("m1", htmlAutocompleter.getModeForColumn(line, 3));
assertEquals("m1", htmlAutocompleter.getModeForColumn(line, 4));
assertEquals("m1", htmlAutocompleter.getModeForColumn(line, 5));
assertEquals("m1", htmlAutocompleter.getModeForColumn(line, 6));
assertEquals("m1", htmlAutocompleter.getModeForColumn(line, 10));
anchor = anchorManager.createAnchor(HtmlAutocompleter.MODE_ANCHOR_TYPE, line,
AnchorManager.IGNORE_LINE_NUMBER, 1);
anchor.setValue("m0");
assertEquals(CodeMirror2.HTML, htmlAutocompleter.getModeForColumn(line, 0));
assertEquals(CodeMirror2.HTML, htmlAutocompleter.getModeForColumn(line, 1));
assertEquals("m0", htmlAutocompleter.getModeForColumn(line, 2));
assertEquals("m1", htmlAutocompleter.getModeForColumn(line, 3));
assertEquals("m1", htmlAutocompleter.getModeForColumn(line, 4));
assertEquals("m1", htmlAutocompleter.getModeForColumn(line, 5));
assertEquals("m1", htmlAutocompleter.getModeForColumn(line, 6));
assertEquals("m1", htmlAutocompleter.getModeForColumn(line, 10));
anchor = anchorManager.createAnchor(HtmlAutocompleter.MODE_ANCHOR_TYPE, line,
AnchorManager.IGNORE_LINE_NUMBER, 5);
anchor.setValue("m2");
assertEquals(CodeMirror2.HTML, htmlAutocompleter.getModeForColumn(line, 0));
assertEquals(CodeMirror2.HTML, htmlAutocompleter.getModeForColumn(line, 1));
assertEquals("m0", htmlAutocompleter.getModeForColumn(line, 2));
assertEquals("m1", htmlAutocompleter.getModeForColumn(line, 3));
assertEquals("m1", htmlAutocompleter.getModeForColumn(line, 4));
assertEquals("m1", htmlAutocompleter.getModeForColumn(line, 5));
assertEquals("m2", htmlAutocompleter.getModeForColumn(line, 6));
assertEquals("m2", htmlAutocompleter.getModeForColumn(line, 10));
anchor = anchorManager.createAnchor(HtmlAutocompleter.MODE_ANCHOR_TYPE, line,
AnchorManager.IGNORE_LINE_NUMBER, 4);
anchor.setValue("m3");
assertEquals(CodeMirror2.HTML, htmlAutocompleter.getModeForColumn(line, 0));
assertEquals(CodeMirror2.HTML, htmlAutocompleter.getModeForColumn(line, 1));
assertEquals("m0", htmlAutocompleter.getModeForColumn(line, 2));
assertEquals("m1", htmlAutocompleter.getModeForColumn(line, 3));
assertEquals("m1", htmlAutocompleter.getModeForColumn(line, 4));
assertEquals("m3", htmlAutocompleter.getModeForColumn(line, 5));
assertEquals("m2", htmlAutocompleter.getModeForColumn(line, 6));
assertEquals("m2", htmlAutocompleter.getModeForColumn(line, 10));
}
/**
* Tests {@link HtmlAutocompleter#putModeAnchors}.
*/
public void testPutModeAnchors() {
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<html"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.WHITESPACE, " "));
prepareAutocompleter();
Document document = helper.editor.getDocument();
Line line = document.getFirstLine();
HtmlAutocompleter htmlAutocompleter = helper.autocompleter.htmlAutocompleter;
// Delete the anchor that was set by prepareAutocompleter().
JsonArray<Anchor> anchors =
AnchorManager.getAnchorsByTypeOrNull(line, HtmlAutocompleter.MODE_ANCHOR_TYPE);
assertEquals(0, anchors.size());
// Modes are empty, the previous line is null.
JsonArray<Pair<Integer, String>> modes = JsonCollections.createArray();
htmlAutocompleter.putModeAnchors(line, modes);
assertTrue(
AnchorManager.getAnchorsByTypeOrNull(line, HtmlAutocompleter.MODE_ANCHOR_TYPE).isEmpty());
// Modes are empty, the previous line is "null object".
htmlAutocompleter.putModeAnchors(line, modes);
assertTrue(
AnchorManager.getAnchorsByTypeOrNull(line, HtmlAutocompleter.MODE_ANCHOR_TYPE).isEmpty());
// Create a line in another document and use it as a not-null previousLine.
Line previousLine = Document.createFromString("").getFirstLine();
assertNull(
AnchorManager.getAnchorsByTypeOrNull(previousLine, HtmlAutocompleter.MODE_ANCHOR_TYPE));
// Modes are empty, the previous line has no mode anchor.
htmlAutocompleter.putModeAnchors(line, modes);
assertTrue(
AnchorManager.getAnchorsByTypeOrNull(line, HtmlAutocompleter.MODE_ANCHOR_TYPE).isEmpty());
// Modes are empty, the previous line has mode anchor.
Anchor previousLineAnchor = previousLine.getDocument().getAnchorManager().createAnchor(
HtmlAutocompleter.MODE_ANCHOR_TYPE, previousLine, AnchorManager.IGNORE_LINE_NUMBER, 0);
previousLineAnchor.setValue("m1");
htmlAutocompleter.putModeAnchors(line, modes);
assertTrue(modes.isEmpty());
anchors = AnchorManager.getAnchorsByTypeOrNull(line, HtmlAutocompleter.MODE_ANCHOR_TYPE);
assertEquals(0, anchors.size());
// Modes are not empty (one mode), the previous line has mode anchor.
modes.add(new Pair<Integer, String>(0, "m2"));
htmlAutocompleter.putModeAnchors(line, modes);
anchors = AnchorManager.getAnchorsByTypeOrNull(line, HtmlAutocompleter.MODE_ANCHOR_TYPE);
assertEquals(1, anchors.size());
assertEquals(0, anchors.get(0).getColumn());
assertEquals("m2", anchors.get(0).getValue());
// Modes are not empty (two modes), the previous line has mode anchor.
modes.add(new Pair<Integer, String>(3, "m3"));
htmlAutocompleter.putModeAnchors(line, modes);
anchors = AnchorManager.getAnchorsByTypeOrNull(line, HtmlAutocompleter.MODE_ANCHOR_TYPE);
assertEquals(2, anchors.size());
assertEquals(0, anchors.get(0).getColumn());
assertEquals("m2", anchors.get(0).getValue());
assertEquals(3, anchors.get(1).getColumn());
assertEquals("m3", anchors.get(1).getValue());
// Modes are not empty (two modes), the previous line is null.
htmlAutocompleter.putModeAnchors(line, modes);
anchors = AnchorManager.getAnchorsByTypeOrNull(line, HtmlAutocompleter.MODE_ANCHOR_TYPE);
assertEquals(2, anchors.size());
assertEquals(0, anchors.get(0).getColumn());
assertEquals("m2", anchors.get(0).getValue());
assertEquals(3, anchors.get(1).getColumn());
assertEquals("m3", anchors.get(1).getValue());
}
/**
* Tests that proposal list is updated when parsing of document is finished.
*/
public void testUpdateOnDocFinish() {
String sampleAttribute = "accesskey";
HtmlTagsAndAttributes htmlAttributes = HtmlTagsAndAttributes.getInstance();
SimpleStringBag excluded = new SimpleStringBag();
assertEquals(1, htmlAttributes.searchAttributes("html", excluded, sampleAttribute).size());
excluded.add(sampleAttribute);
JsonArray<Token> tokens1 = JsonCollections.createArray();
tokens1.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<html"));
tokens1.add(new Token(CodeMirror2.HTML, TokenType.WHITESPACE, " "));
String line1 = tokensToText(tokens1);
parsedLines.put(line1, tokens1);
JsonArray<Token> tokens2 = JsonCollections.createArray();
tokens2.add(new Token(CodeMirror2.HTML, TokenType.ATTRIBUTE, sampleAttribute));
String line2 = tokensToText(tokens2);
parsedLines.put(line2, tokens2);
JsonArray<Token> tokens3 = JsonCollections.createArray();
tokens3.add(new Token(CodeMirror2.HTML, TokenType.WHITESPACE, " "));
String line3 = tokensToText(tokens3);
parsedLines.put(line3, tokens3);
String text = line1 + "\n" + line2 + "\n ";
helper.setup(path, text, 0, line1.length(), false);
helper.parser.getListenerRegistrar().add(new DocumentParserListenerAdapter(
helper.autocompleter, helper.editor));
helper.parser.begin();
parseOneLine();
helper.autocompleter.requestAutocomplete();
// "...please wait..."
assertEquals(1, helper.popup.proposals.size());
parseOneLine();
// Still "...please wait..."
assertEquals(1, helper.popup.proposals.size());
parseOneLine();
assertEquals(htmlAttributes.searchAttributes("html", excluded, "").size(),
helper.popup.proposals.size());
}
/**
* Tests that find autocompletions do not ruin existing "clean" results.
*/
public void testFindDoNotRuinResults() {
String id = "id";
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<html"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.WHITESPACE, " "));
prepareAutocompleter();
HtmlTagWithAttributes before = helper.editor.getDocument().getFirstLine().getTag(
XmlCodeAnalyzer.TAG_END_TAG);
assertNotNull(before);
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.ATTRIBUTE, id));
helper.autocompleter.htmlAutocompleter.findAutocompletions(
helper.editor.getSelection(), CTRL_SPACE);
HtmlTagWithAttributes after = helper.editor.getDocument().getFirstLine().getTag(
XmlCodeAnalyzer.TAG_END_TAG);
assertTrue("reference equality", before == after);
assertFalse("tag modifications", after.getAttributes().contains(id));
}
/**
* Tests that used attributes are excluded.
*/
public void testExcludedHtmlAttributes() {
String reversed = "reversed";
HtmlTagsAndAttributes htmlAttributes = HtmlTagsAndAttributes.getInstance();
SimpleStringBag excluded = new SimpleStringBag();
assertEquals(1, htmlAttributes.searchAttributes("ol", excluded, reversed).size());
excluded.add(reversed);
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<ol"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.WHITESPACE, " "));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.ATTRIBUTE, reversed));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.ATOM, "="));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.STRING, "\"\""));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.WHITESPACE, " "));
AutocompleteProposals proposals = findAutocompletions();
assertEquals(htmlAttributes.searchAttributes("ol", excluded, "").size(), proposals.size());
assertEquals("accesskey", proposals.get(0).getName());
assertNull(TestUtils.selectProposalByName(proposals, reversed));
}
/**
* Tests the proposals for ELEMENT.
*/
public void testAutocompleteHtmlElements() {
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<a"));
AutocompleteProposals proposals = findAutocompletions();
assertEquals(7, proposals.size());
assertEquals("abbr", proposals.get(1).getName());
lineTokens.clear();
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<bod"));
proposals = findAutocompletions();
assertEquals(1, proposals.size());
assertEquals("body", proposals.get(0).getName());
lineTokens.clear();
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<body"));
assertEquals(1, findAutocompletions().size());
lineTokens.clear();
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<body"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, ">"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "</body"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, ">"));
assertTrue(findAutocompletions().isEmpty());
lineTokens.clear();
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<"));
assertEquals(
HtmlTagsAndAttributes.getInstance().searchTags("").size(), findAutocompletions().size());
}
/**
* Tests the autocompletion of self-closing tag.
*/
public void testAutocompleteSelfClosingTag() {
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<lin"));
AutocompleteProposals autocompletions = findAutocompletions();
assertNotNull(autocompletions);
ProposalWithContext linkProposal = TestUtils.selectProposalByName(autocompletions, "link");
assertNotNull(linkProposal);
AutocompleteResult commonResult =
helper.autocompleter.htmlAutocompleter.computeAutocompletionResult(linkProposal);
assertTrue("result type", commonResult instanceof DefaultAutocompleteResult);
DefaultAutocompleteResult result = (DefaultAutocompleteResult) commonResult;
assertEquals(4, result.getJumpLength());
assertEquals("link />", result.getAutocompletionText());
}
/**
* Tests full autocompletion for ATTRIBUTE.
*/
public void testJumpLengthAndFullAutocompletionHtmlAttribute() {
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<body"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.WHITESPACE, " "));
AutocompleteProposals autocompletions = findAutocompletions();
assertNotNull(autocompletions);
ProposalWithContext onloadProposal = TestUtils.selectProposalByName(autocompletions, "onload");
assertNotNull(onloadProposal);
AutocompleteResult commonResult =
helper.autocompleter.htmlAutocompleter.computeAutocompletionResult(onloadProposal);
assertTrue("result type", commonResult instanceof DefaultAutocompleteResult);
DefaultAutocompleteResult result = (DefaultAutocompleteResult) commonResult;
assertEquals(8, result.getJumpLength());
String fullAutocompletion = "onload=\"\"";
assertEquals(fullAutocompletion, result.getAutocompletionText());
}
/**
* Tests full autocompletion for ELEMENT.
*/
public void testJumpLengthAndFullAutocompletionHtmlElement() {
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<bod"));
AutocompleteProposals autocompletions = findAutocompletions();
assertNotNull(autocompletions);
ProposalWithContext bodyProposal = TestUtils.selectProposalByName(autocompletions, "body");
assertNotNull(bodyProposal);
AutocompleteResult commonResult =
helper.autocompleter.htmlAutocompleter.computeAutocompletionResult(bodyProposal);
assertTrue("result type", commonResult instanceof DefaultAutocompleteResult);
DefaultAutocompleteResult result = (DefaultAutocompleteResult) commonResult;
assertEquals(5, result.getJumpLength());
String fullAutocompletion = "body></body>";
assertEquals(fullAutocompletion, result.getAutocompletionText());
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/html/XmlCodeAnalyzerTest.java | javatests/com/google/collide/client/code/autocomplete/html/XmlCodeAnalyzerTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.html;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.collide.codemirror2.CodeMirror2;
import com.google.collide.codemirror2.Token;
import com.google.collide.codemirror2.TokenType;
import com.google.collide.json.shared.JsonArray;
import com.google.collide.json.shared.JsonStringMap;
import com.google.collide.shared.TaggableLine;
import com.google.collide.shared.util.JsonCollections;
/**
* Tests for xml {@link XmlCodeAnalyzer}
*
*/
public class XmlCodeAnalyzerTest extends SynchronousTestCase {
private static class MockTagHolder implements TaggableLine {
JsonStringMap<Object> tags = JsonCollections.createMap();
@Override
@SuppressWarnings("unchecked")
public <T> T getTag(String key) {
return (T) tags.get(key);
}
@Override
public <T> void putTag(String key, T value) {
tags.put(key, value);
}
@Override
public TaggableLine getPreviousLine() {
throw new IllegalStateException("unexpected call");
}
@Override
public boolean isFirstLine() {
return false;
}
@Override
public boolean isLastLine() {
return false;
}
}
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
public void testParse() {
XmlCodeAnalyzer codeAnalyzer = new XmlCodeAnalyzer();
JsonArray<TaggableLine> lines = JsonCollections.createArray();
JsonArray<JsonArray<Token>> tokens = JsonCollections.createArray();
// NOTE: 0 is used for line before the beginning of document.
for (int i = 0; i <= 3; i++) {
lines.add(new MockTagHolder());
tokens.add(JsonCollections.<Token>createArray());
}
JsonArray<Token> lineTokens;
lineTokens = tokens.get(1);
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<html"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.ATTRIBUTE, "first"));
lineTokens = tokens.get(2);
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.ATTRIBUTE, "second"));
lineTokens = tokens.get(3);
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.ATTRIBUTE, "third"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, ">"));
codeAnalyzer.onBeforeParse();
for (int i = 1; i <= 3; i++) {
codeAnalyzer.onParseLine(lines.get(i - 1), lines.get(i), tokens.get(i));
}
codeAnalyzer.onAfterParse();
assertNull(lines.get(1).getTag(XmlCodeAnalyzer.TAG_START_TAG));
HtmlTagWithAttributes tag = lines.get(1).getTag(XmlCodeAnalyzer.TAG_END_TAG);
assertNotNull(tag);
assertEquals("html", tag.getTagName());
assertTrue(tag.getAttributes().contains("first"));
assertTrue(tag.getAttributes().contains("second"));
assertTrue(tag.getAttributes().contains("third"));
assertTrue(tag == lines.get(2).getTag(XmlCodeAnalyzer.TAG_START_TAG));
assertTrue(tag == lines.get(2).getTag(XmlCodeAnalyzer.TAG_END_TAG));
assertTrue(tag == lines.get(3).getTag(XmlCodeAnalyzer.TAG_START_TAG));
assertNull(lines.get(3).getTag(XmlCodeAnalyzer.TAG_END_TAG));
}
public void testReparse() {
XmlCodeAnalyzer codeAnalyzer = new XmlCodeAnalyzer();
JsonArray<TaggableLine> lines = JsonCollections.createArray();
JsonArray<JsonArray<Token>> tokens = JsonCollections.createArray();
// NOTE: 0 is used for line before the beginning of document.
for (int i = 0; i <= 3; i++) {
lines.add(new MockTagHolder());
tokens.add(JsonCollections.<Token>createArray());
}
JsonArray<Token> lineTokens;
lineTokens = tokens.get(1);
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<html"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.ATTRIBUTE, "first"));
lineTokens = tokens.get(2);
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.ATTRIBUTE, "second"));
lineTokens = tokens.get(3);
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.ATTRIBUTE, "third"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, ">"));
codeAnalyzer.onBeforeParse();
for (int i = 1; i <= 3; i++) {
codeAnalyzer.onParseLine(lines.get(i - 1), lines.get(i), tokens.get(i));
}
codeAnalyzer.onAfterParse();
lineTokens = tokens.get(2);
lineTokens.clear();
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.ATTRIBUTE, "fixed"));
codeAnalyzer.onBeforeParse();
for (int i = 2; i <= 3; i++) {
codeAnalyzer.onParseLine(lines.get(i - 1), lines.get(i), tokens.get(i));
}
codeAnalyzer.onAfterParse();
assertNull(lines.get(1).getTag(XmlCodeAnalyzer.TAG_START_TAG));
HtmlTagWithAttributes tag = lines.get(1).getTag(XmlCodeAnalyzer.TAG_END_TAG);
assertNotNull(tag);
assertEquals("html", tag.getTagName());
assertTrue(tag.getAttributes().contains("first"));
assertTrue(tag.getAttributes().contains("fixed"));
assertTrue(tag.getAttributes().contains("third"));
assertTrue(tag == lines.get(2).getTag(XmlCodeAnalyzer.TAG_START_TAG));
assertTrue(tag == lines.get(2).getTag(XmlCodeAnalyzer.TAG_END_TAG));
assertTrue(tag == lines.get(3).getTag(XmlCodeAnalyzer.TAG_START_TAG));
assertNull(lines.get(3).getTag(XmlCodeAnalyzer.TAG_END_TAG));
}
public void testIntermediateTags() {
XmlCodeAnalyzer codeAnalyzer = new XmlCodeAnalyzer();
JsonArray<TaggableLine> lines = JsonCollections.createArray();
JsonArray<JsonArray<Token>> tokens = JsonCollections.createArray();
// NOTE: 0 is used for line before the beginning of document.
for (int i = 0; i <= 2; i++) {
lines.add(new MockTagHolder());
tokens.add(JsonCollections.<Token>createArray());
}
JsonArray<Token> lineTokens;
lineTokens = tokens.get(1);
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<first"));
lineTokens = tokens.get(2);
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.ATTRIBUTE, "first"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, ">"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<second"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.ATTRIBUTE, "second"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, ">"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<third"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.ATTRIBUTE, "third"));
codeAnalyzer.onBeforeParse();
for (int i = 1; i <= 2; i++) {
codeAnalyzer.onParseLine(lines.get(i - 1), lines.get(i), tokens.get(i));
}
codeAnalyzer.onAfterParse();
assertNull(lines.get(1).getTag(XmlCodeAnalyzer.TAG_START_TAG));
HtmlTagWithAttributes tag = lines.get(1).getTag(XmlCodeAnalyzer.TAG_END_TAG);
assertNotNull(tag);
assertEquals("first", tag.getTagName());
assertTrue(tag.getAttributes().contains("first"));
assertTrue(tag == lines.get(2).getTag(XmlCodeAnalyzer.TAG_START_TAG));
assertFalse(tag == lines.get(2).getTag(XmlCodeAnalyzer.TAG_END_TAG));
tag = lines.get(2).getTag(XmlCodeAnalyzer.TAG_END_TAG);
assertNotNull(tag);
assertEquals("third", tag.getTagName());
assertTrue(tag.getAttributes().contains("third"));
}
public void testDeleteLine() {
XmlCodeAnalyzer codeAnalyzer = new XmlCodeAnalyzer();
JsonArray<TaggableLine> lines = JsonCollections.createArray();
JsonArray<JsonArray<Token>> tokens = JsonCollections.createArray();
// NOTE: 0 is used for line before the beginning of document.
for (int i = 0; i <= 3; i++) {
lines.add(new MockTagHolder());
tokens.add(JsonCollections.<Token>createArray());
}
JsonArray<Token> lineTokens;
lineTokens = tokens.get(1);
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, "<html"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.ATTRIBUTE, "first"));
lineTokens = tokens.get(2);
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.ATTRIBUTE, "second"));
lineTokens = tokens.get(3);
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.ATTRIBUTE, "third"));
lineTokens.add(new Token(CodeMirror2.HTML, TokenType.TAG, ">"));
codeAnalyzer.onBeforeParse();
for (int i = 1; i <= 3; i++) {
codeAnalyzer.onParseLine(lines.get(i - 1), lines.get(i), tokens.get(i));
}
codeAnalyzer.onAfterParse();
codeAnalyzer.onLinesDeleted(JsonCollections.createArray(lines.get(2)));
assertNull(lines.get(1).getTag(XmlCodeAnalyzer.TAG_START_TAG));
HtmlTagWithAttributes tag = lines.get(1).getTag(XmlCodeAnalyzer.TAG_END_TAG);
assertNotNull(tag);
assertEquals("html", tag.getTagName());
assertTrue(tag.getAttributes().contains("first"));
assertTrue(tag.getAttributes().contains("third"));
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
WeTheInternet/collide | https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/javatests/com/google/collide/client/code/autocomplete/html/HtmlTagsAndAttributesTest.java | javatests/com/google/collide/client/code/autocomplete/html/HtmlTagsAndAttributesTest.java | // Copyright 2012 Google Inc. 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.
package com.google.collide.client.code.autocomplete.html;
import com.google.collide.client.code.autocomplete.AutocompleteProposal;
import com.google.collide.client.testutil.SynchronousTestCase;
import com.google.collide.client.util.collections.SimpleStringBag;
import com.google.collide.json.shared.JsonArray;
/**
* Test cases for {@link HtmlTagsAndAttributes}.
*
*/
public class HtmlTagsAndAttributesTest extends SynchronousTestCase {
@Override
public String getModuleName() {
return "com.google.collide.client.TestCode";
}
/**
* Tests that used attributes are excluded.
*/
public void testExclusion() {
HtmlTagsAndAttributes htmlAttributes = HtmlTagsAndAttributes.getInstance();
SimpleStringBag excluded = new SimpleStringBag();
JsonArray<AutocompleteProposal> all = htmlAttributes
.searchAttributes("html", excluded, "");
assertNotNull(all);
assertTrue(all.size() > 3);
excluded.add(all.get(2).getName());
JsonArray<AutocompleteProposal> allButOne = htmlAttributes
.searchAttributes("html", excluded, "");
assertNotNull(allButOne);
assertTrue(all.size() == allButOne.size() + 1);
}
/**
* Tests that attribute names are (prefix-)filtered.
*/
public void testFiltering() {
HtmlTagsAndAttributes htmlAttributes = HtmlTagsAndAttributes.getInstance();
SimpleStringBag excluded = new SimpleStringBag();
JsonArray<AutocompleteProposal> all = htmlAttributes
.searchAttributes("html", excluded, "");
assertNotNull(all);
JsonArray<AutocompleteProposal> oneLetterFiltered = htmlAttributes
.searchAttributes("html", excluded, "i");
assertNotNull(oneLetterFiltered);
JsonArray<AutocompleteProposal> twoLettersFiltered = htmlAttributes
.searchAttributes("html", excluded, "it");
assertNotNull(twoLettersFiltered);
assertTrue(all.size() > oneLetterFiltered.size());
for (AutocompleteProposal proposal : oneLetterFiltered.asIterable()) {
assertTrue(proposal.getName().startsWith("i"));
}
assertTrue(oneLetterFiltered.size() > twoLettersFiltered.size());
for (AutocompleteProposal proposal : twoLettersFiltered.asIterable()) {
assertTrue(proposal.getName().startsWith("it"));
}
}
}
| java | Apache-2.0 | 2136cfc9705a96d88c69356868dda5b95c35bc6d | 2026-01-05T02:34:36.415338Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.